spring

Spring MVC 4 + hibernate 4 integration example

This quick guide will help you on start with Spring MVC and Hibernate. In this tutorial i will make a simple insert form and a list form. This web application will do follow thing:

  • Add Employee.
  • Allow query all employee inserted.

Well, let’s start

1. Technologies

We using following technologies:

  • Eclipse Kepler
  • Spring MVC 4
  • Hibernate 4
  • Mysql

2. Project Structure

 

3. Dependencies

We need following in our dependencies

<!-- Spring MVC -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <!-- Hibernate -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernate-version}</version>
    </dependency>
    <!-- Mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.2.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- DBCP connection pool -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!-- Taglib -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

${spring-version} is property for spring version. I use version 4.0.3.RELEASE.
${hibernate-version} is property for Hibernate version. I use version 4.3.4.Final.
4. Spring controllers

We have two controllers in this tutorial: AddEmployeeController,ListEmployeeController
ListEmployeeController: using to list all employees inserted in database

@Controller
@RequestMapping("/manage/list.do")
public class ListEmployeeController extends BaseController {
  @Autowired
  private EmployeeService employeeService;

  /**
   * contructor
   */
  public ListEmployeeController() {
    setSuccessView("list");
  }

  @RequestMapping(method = RequestMethod.GET)
  public String list(Model  model) {
    List list=employeeService.listAll();
    model.addAttribute("employees", list);
    model.addAttribute("test", "Hello");
    return getSuccessView();
  }

}

AddEmployeeController: using to handle insert employee

@Controller
@RequestMapping("/manage/add.do")
public class AddEmployeeController extends BaseController {
  @Autowired
  private EmployeeService employeeService;

  /**
   * Contructor
   */
  public AddEmployeeController() {
    super();
    setSuccessView("add");
    setRedirectView("redirect:/manage/add.do");
  }

  @RequestMapping(method = RequestMethod.GET)
  public String add(Model model,HttpSession session) {
    if(session.getAttribute("message")!=null){
      model.addAttribute("message", "Insert employee successful.");
      session.removeAttribute("message");
    }
    return getSuccessView();
  }

  @RequestMapping(method = RequestMethod.POST)
  public String process(@ModelAttribute EmployeeForm employee,HttpSession session) {
    Employee emp = new Employee();
    emp.setEmail(employee.getEmail());
    emp.setPhone(employee.getPhone());
    emp.setLastName(employee.getLastName());
    emp.setFirstName(employee.getFirstName());
    session.setAttribute("message", "Insert employee successful.");
    employeeService.insert(emp);

    return getRedirectView();
  }

  @ModelAttribute(value = "employee")
  public EmployeeForm createModelAttribute() {
    return new EmployeeForm();
  }

}

5. Service and DAO

We create a service to perform business insert/list employee(s) and service will call to DAO to perform database manipulate
EmployeeService.class

@Component
public class EmployeeService {
  @Autowired
  private EmployeeDAO employeeDAO;

  @Transactional(readOnly = true)
  public List listAll() {
    return employeeDAO.listAll();
  }
  @Transactional(rollbackFor = {Exception.class})
  public Employee insert(Employee emp) {
    return employeeDAO.insert(emp);
  }
}

@Component: we using this to avoid define bean on xml config, spring will scan and register this bean with bean container.

EmployeeDAO.class

@Component
public class EmployeeDAO {
  @Autowired
  private SessionFactory sf;

  public Employee insert(Employee emp) {
    Session session = sf.getCurrentSession();
    session.save(emp);
    return emp;
  }

  public Employee update(Employee emp) {
    Session session = sf.getCurrentSession();
    session.update(emp);
    return emp;
  }

  @SuppressWarnings("unchecked")
  public List listAll() {
    Session session = sf.getCurrentSession();
    return session.createCriteria(Employee.class).list();
  }

}

we inject SessionFactory to DAO and manipulate with database through hibernate.
6. Spring configuration

We define sessionFactory for hibernate, also need declare component scan for Spring find bean and auto register with bean container.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  <annotation-driven />
  <tx:annotation-driven/>
  <context:component-scan base-package="com.devjav.controller,com.devjav.dao,com.devjav.service" />
  <!-- View Resolver -->
  <beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
  </beans:bean>
  <!-- Datasource -->
  <beans:bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <beans:property name="url" value="jdbc:mysql://localhost:3306/tutorial" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="admin" />
  </beans:bean>
  <!-- Hibernate sessionfactory -->
  <beans:bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="datasource" />
    <beans:property name="annotatedClasses">
      <beans:list>
        <beans:value>com.devjav.domain.Employee</beans:value>
      </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
      <beans:props>
        <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</beans:prop>
        <beans:prop key="hibernate.show_sql">true</beans:prop>
        <beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
      </beans:props>
    </beans:property>
  </beans:bean>
  <beans:bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager"
    p:sessionFactory-ref="sessionFactory">
  </beans:bean>
</beans:beans>

7. Soure code
You can get source code in following link

One thought on “Spring MVC 4 + hibernate 4 integration example”

Leave a Reply