Today I would like to demonstrate how to use Hibernate in Spring framework to do the data manipulation works in MySQL database.I will use spring mvc 3, hibernate 4 frameworks and spring annotation for bean creation and also generic dao class for data manipulation works.
Step 1: Mysql employee Table Creation.
This is the employee table structure.
CREATE TABLE `employee` (
`ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
`ADDRESS` VARCHAR(255) NOT NULL,
`CONTACT_NUMBER` VARCHAR(30) NOT NULL,
`NAME` VARCHAR(20) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `ID` (`ID`)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1
Now create a Maven web project using eclipse or NetBeans.
We can use generic DAO class for common methods such as save, update, delete, findAll.. which are required in every DAO class. We will create Genericdao and GenericDaoimpl for common methods.
public interface GenericDao <e extends serializable > {
List <e> findAll();
E findById(Long id);
void saveOrUpdate(E e);
void delete(E e);
List <e> findByCriteria(Criterion criterion);
}
What is core java and advanced java?
Before we start talking about java framework, we should know about core and advance java.
Core java comes with java 'Standard Edition' and it has to do with the basic package of Java objects that are typically used for general desktop applications.
Where as advance java is specialisation in some domain, such as networking, web, DCOM or database handling.
What is Frameworks?
Framework is set of reusable software program that forms the basis for an application. Frameworks helps the programmers to build the application quickly. Earlier it was very hard to develop complex web applications. Now it’s very easy to develop such application using different kinds of frameworks such as Struts, Struts 2, Hibernate, JSF, Tapestry, JUnit, Log4j, Spring etc.
http://www.roseindia.net/frameworks/
Example of Java frameworks
MVC frameworks : Spring
ORM frameworks : Hibernate, Oracle TopLink, iBATIS
Presentation layer frameworks : Struts, JSF, Apache Wicket
Example of Framework usage
I will show how JDBC that inserts data into the database and how simply do it using java frameworks(Spring & Hibernate).
Consider there is a Customer table in your database.
That’s it. That’s what all we need to do. @Transactional annotation will handle the transactional part in database access and hibernate session’s save method will insert customer data into table.If anything goes wrong and Exception throws,this method will rollback transaction.
(to achieve this we need to do some configurations like Datasource, HibernateSessionFactory, TransactionManager spring beans)
There are so many example like this,when you develop application using java frameworks.Main advantage is we can concentrate our application business logic rather than handling data access common boilerplate code.
Other than this some of advantage of frameworks are