How To Integrate Spring With JPA Hibernate In Java Development

1) Eclipse IDE
2) Maven
3) Spring 3.x
4) Hibernate 4.x

1) Create Maven Project

a. Open Eclipse IDE » Goto File » New » Other » Maven Project.
b. On the next screen check ON create a simple project (skip archetype selection).
c. fill up the mandatory input fields.
d. group id : (package name for the build)
d. artifact id (it will be the name of the project).
e. packaging : it should be WAR in our case, click Finish.

You have now a blank maven project.

2) pom.xml : add required dependencies for Spring – JPA - Hibernate

We will start with adding required dependencies to pom.xml file for Spring – JPA – Hibernate.

a. set properties to access version globally

    <properties>
        <spring.version>3.2.5.RELEASE</spring.version>
        <hibernate.version>4.1.9.Final</hibernate.version>
    </properties>

b. add dependencies for spring

<dependencies>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

    </dependencies>

c. then add dependencies for spring ORM

        <!-- Spring to Integrate with ORM -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</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-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

d. now add dependencies for hibernate JPA

<!-- Hibernate JPA -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!-- JDBC Pools -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>

e. now add connector for your specific database, as we are using mysql we will add connector for mysql.

<!-- MySql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.18</version>
        </dependency>

f. and finally logging dependencies

<!-- Logging -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.6.0</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.0</version>
        </dependency>

Thats it you have added all the required dependencies to integrate spring with hibernate jpa.

3) Now we will create one table to the database for this example. Go to mysql and created below table.

Employee
Emplid Integer
first_name Varchar
last_name Varchar

4) Create a JPA Entity Object for above table to the project.

Employee.java

package com.aegis.ws.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
@NamedQuery(name = "employee.findByEmplid", query = "select e from Employee e where e.empId = :emplid")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "emplid")
    private Long empId;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    // Getter Setter

    public Long getEmpId() {
        return empId;
    }

    public void setEmpId(Long empId) {
        this.empId = empId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

5) Now its time to Create a DAO Layer that connect and used to retrieve JPA entity from database.

We will first create DAO interface and then its implementation.

EmployeeDAO.java

package com.aegis.ws.rest.dao;
import java.util.List;
import com.aegis.ws.model.Employee;

public interface EmployeeDAO {
    public List<Employee> getAllEmployees();
    public Employee getEmployeeById(Long empId);
}

EmployeeDAOImpl.java

package com.aegis.ws.rest.dao.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import com.aegis.ws.model.Employee;
import com.aegis.ws.rest.dao.EmployeeDAO;

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {

    @PersistenceContext
    private EntityManager entityManager;

    public List<Employee> getAllEmployees() {
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Employee> empCQ = builder.createQuery(Employee.class);

        Root<Employee> root = empCQ.from(Employee.class);
        empCQ.select(root);

        return entityManager.createQuery(empCQ).getResultList();
    }

    public Employee getEmployeeById(Long empId) {
        Employee employee = null ;
        TypedQuery<Employee> query =  entityManager.createNamedQuery("employee.findByEmplid", Employee.class);
        query.setParameter("emplid", empId);
        try {
            employee = query.getSingleResult() ;
        } catch (javax.persistence.NoResultException ex) {
            //logger.warn("No Employee was found with an emplid of " + emplid);
        }
        return employee;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}

Here we have declared two method one that retrieves all employees from db and another one that retrieves based on empId, input parameter passed to the method.

Private field EntityManger will be injected through the JPA @PersistenceContext

Good going upto now we have created DAO layer and next step would be the service/business layer.

6) Create a Service/Business Layer that connects with DAO Layer.

EmployeeService.java

package com.aegis.ws.rest.services;

import java.util.List;
import com.aegis.ws.model.Employee;

public interface EmployeeService {
    public List<Employee> getAllEmployees();
    public Employee getEmployeeById(Long empId);
}

EmployeeServiceImpl.java

package com.aegis.ws.rest.services.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aegis.ws.model.Employee;
import com.aegis.ws.rest.dao.EmployeeDAO;
import com.aegis.ws.rest.services.EmployeeService;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeDAO employeeDAO;

    public List<Employee> getAllEmployees() {
        return employeeDAO.getAllEmployees();
    }

    public Employee getEmployeeById(Long empId) {
        return employeeDAO.getEmployeeById(empId);
    }

    public void setEmployeeDAO(EmployeeDAO employeeDAO) {
        this.employeeDAO = employeeDAO;
    }
}

We created a service layer that will communicate with the DAO layer and provide operations to the request client.

Here EmployeeDAO will get injected through the @Autowired annotation.

7) Our next step is to create persistence file.

As we are integrating Hibernate with JPA, in any JPA application it is required to create persistence unit, and all the JPA entity definition goes into the persistence.xml file.

Path : /src/main/resources/META-INF/persistence.xml
7) Our next step is to create persistence file.

As we are integrating Hibernate with JPA, in any JPA application it is required to create persistence unit, and all the JPA entity definition goes into the persistence.xml file.

Path : /src/main/resources/META-INF/persistence.xml

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="jerseySpringJpaPU"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <class>com.aegis.ws.model.Employee</class>

        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <!-- value='create' to build a new database on each run; value='update' 
                to modify an existing database; value='create-drop' means the same as 'create' 
                but also drops tables when Hibernate closes; value='validate' makes no changes 
                to the database -->
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.use_sql_comments" value="true" />
        </properties>
    </persistence-unit>

</persistence>

Above you can see The <provider> is defined as HibernatePersistence because here we are using Hibernate as the JPA implementation, and we have MYSQL as a backend we have provided mysql dialect.

8) Finally we need to Create Spring configuration file (applicationContext.xml)

Register beans with it and also enable component-scan feature that scans classpath to auto-register annotated components.

applicationContext.xml

<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" xmlns:p="http://www.springframework.org/schema/p"
    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.xsd">

    <tx:annotation-driven />
    <context:component-scan base-package="com.aegis.ws.rest" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/aegis" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/aegis" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="MYSQL" />
                <property name="showSql" value="true" />
            </bean>
        </property>
    </bean>

    <bean id="employeeService"         class="com.aegis.ws.rest.services.impl.EmployeeServiceImpl" />

    <bean id="employeeDAO" class="com.aegis.ws.rest.dao.impl.EmployeeDAOImpl" />

</beans>

Done : you are done with the integration.

9) Its now time to Test you application

Let create simple java class to test out application.

TestJPA.java

public class TestJPA {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext( "<path_to>/applicationContext.xml");
        EmployeeService employeeService = (EmployeeService) ctx.getBean("aegisEmployeeService");
        List<Employee> list = employeeService.getAllEmployees ();
        System.out.println("Employee count: " + list.size());
    }
}

After running the test class, it will generate the below output.

Employee count: <no>

Senior Java development team can use the above shared coding and integrate Spring 3.x with JPA/ Hibernate 4.x. For hiring java developers or outsourcing your project, contact Aegis experts.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License