In this post we will be discussing on Spring Hibernate integration. As we all know Spring provides an ORM support and one of the best available ORM tool to be integrated with Spring is Hibernate. The integration is very much simple and comes with lot of flexibility which is the biggest advantage Spring comes with. Lest create a step wise project for simple application.
Project Structure
Create a Dynamic Web Project in your eclipse, lets say “Spring-Hibernate-Integration”. Add the required jar files for Spring and Hibernate and add the runtime environment, in this case we are adding Apache Tomcat 7. At the end our project structure and the required dependencies in the lib folder will be as shown below.
The libraries to be added –
Configuration (XML and Properties)
- WEB.XML file – It contains simple mapping of dispatcher servlet along with the welcome page to load.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Spring-Hibernate-Integration</display-name> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>jsp/welcome.jsp</welcome-file> </welcome-file-list> </web-app> |
2. dispatcher-servlet.xml – It contains the details of Spring and hibernate beans to be used along with the configurations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <context:property-placeholder location="classpath:jdbc.properties" /> <context:component-scan base-package="com.code2java" /> <tx:annotation-driven transaction-manager="hibernateTransactionManager" /> <!-- JSP View resolver --> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- Bean for Database driver and details --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${database.driver}" /> <property name="url" value="${database.url}" /> <property name="username" value="${database.user}" /> <property name="password" value="${database.password}" /> </bean> <!-- Session Factory for using data source --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> </props> </property> <!-- List of Beans that will be mapped to the Database table --> <property name="annotatedClasses"> <list> <value>com.code2java.bean.User</value> </list> </property> </bean> <!-- Allowing Hibernate to maintain the Transactions on its own using Transaction Manager Transactions will be done using Session Factory created above for the DataSrurce --> <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans> |
In this configuration file, we have created a bean for data source, session factory and transaction manager. All these three beans will be used for all the transactions with the data base. Data source bean will give the details about the data base and will give the connection object. Session factory will create the session from the given data source so that transaction can be done using transaction manager with the data base. Transaction manager will make sure that all the transactions are safe and will take care of clearing and maintaining sessions in the server. While creating the session factory we have mentioned a bean that will be mapped to the data base table “users”. Please note, you can also configure such annotated beans apart from this xml file that is in your java files.
3. jdbc.properties file : This file contains the details of database like, driver, port, username, password, url etc. This file will be loaded in the dispatcher servlet to read the details and create a datasource.
1 2 3 4 5 6 |
database.driver=com.mysql.jdbc.Driver database.url=jdbc:mysql://localhost:3306/code2java database.user=root database.password=root hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true |
View Pages:
Lets create a JSP page which contains a form that will submit the data to the server to be stored in data base. Along with this, it will load all the user available in the database along with the current user submitted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>code2java - Spring Hibernate Integration</title> </head> <body> <form method="post" action="addUser.do" modelAttribute="user"> <table> <tr> <td><label>Name</label></td> <td><input type="text" name="name"></td> </tr> <tr> <td><label>UserName</label></td> <td><input type="text" name="userName"></td> </tr> <tr> <td><label>Email</label></td> <td><input type="text" name="email"></td> </tr> <tr> <td><label>Password</label></td> <td><input type="password" name="password"></td> </tr> <tr> <td colspan="2"><input type="Submit" value="Submit"></td> </tr> </table> </form> <br /> <b>Users Available : </b> <table border="1px solid" style="border-collapse: collapse;"> <tr> <th>User</th> <th>Email</th> </tr> <c:forEach var="list" items="${model}"> <tr> <td>${list.name}</td> <td>${list.email}</td> </tr> </c:forEach> </table> </body> </html> |
Controllers, Services and Beans
Lets create a controller class for mapping the requests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.code2java.controllers; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.code2java.bean.User; import com.code2java.service.UserServiceImpl; @Controller public class MainController { @Autowired private UserServiceImpl userService; @RequestMapping("addUser") public ModelAndView addUser(@ModelAttribute("user") User user, BindingResult result, HttpServletRequest request, HttpServletResponse response) { userService.addUser(user); List<User> model = userService.getUserList(); return new ModelAndView("welcome","model", model); } } |
The controller class requires a UserService to process the request and a User model to process on. Lets create a user service and a user DAO which will process user bean that is be mapped to the data base table “users”.
User Service Interface and implementation:
1 2 3 4 5 6 7 8 9 10 11 |
package com.code2java.service; import java.util.List; import com.code2java.bean.User; public interface IUserService { public void addUser(User user); public List<User> getUserList(); } |
User Service Implementation :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.code2java.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.code2java.bean.User; import com.code2java.dao.UserDAO; @Service("userService") public class UserServiceImpl implements IUserService { @Autowired private UserDAO userDao; @Override public void addUser(User user) { userDao.addUser(user); } @Override public List<User> getUserList() { return userDao.getUser(); } } |
User bean that consists of the mapping of each row to a single property of this POJO class. @Entity and @Table(name = “users”) annotations are used in the below bean class to map the bean with the “users” table in the data base. Each column is mapped to one of the columns in the table using @Column annotation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package com.code2java.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "users") public class User { @Id @GeneratedValue @Column(name = "id") private int id; @Column(name = "userName") private String name; @Column(name = "password") private String password; @Column(name = "email") private String email; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
UserDAO class to process the transactions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com.code2java.dao; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.code2java.bean.User; @Repository("userDao") public class UserDAO { @Autowired SessionFactory sessionFactory; @Transactional public void addUser(User user) { sessionFactory.getCurrentSession().save(user); } @Transactional public List<User> getUser() { @SuppressWarnings("unchecked") List<User> userlist = sessionFactory.getCurrentSession().createCriteria(User.class).list(); return userlist; } } |
Output
And we are done with the coding part now. Just execute your application on the server and see the results. In this case the output will be-
First page :
Initial table details before any submission :
Data submission :
Data submission response:
Table content after the data submission :
Hope this helps you.
Regards,
Nikhil Naoghare.