Spring Hibernate Integration Using Java Persistence API

Prerequisite Trails

Spring Hibernate Dao Support

Spring Hibernate Integration using SessionFactory

Concept Overview

JPA (Java Persistence API) – JPA is a persistence framework for Object Relational Mapping. It is based on POJO (Plain Old Java Object). It was born out of the complexity experienced in EJB2. It can be used in both EJB and non-EJB context.

EntityManager– EntityManager is part of the persistence API. The instance of EntityManager is associated with a persistence context. The EntityManager has methods such as persist, merge, remove, find etc. The persist method, for example, takes in an Entity and persists it. The EntityManager is produced by an implementation of EntityManagerFactory. The Entity Manager may be managed by the application (Application managed Entity Manager) or by the container (Container Manager Entity Manager).

LocalEntityManagedFactoryBean – This is a spring FactoryBean that creates an EntityManagerFactory. This is configured as spring bean and then injected into the DAO as a property. The configuration settings are passed through META-INF/persistence.xml. persistence.xml contains one or more persistence units. The persistence units contains one or more persistence classes along with the data source and mapping files. The persistence Unit is then injected into the LocalEntityManagedFactoryBean configuration in spring xml. Note that for spring, there is not much advantage in using a LocalEntityManagedFactoryBean.

LocalContainerManagedFactoryBean– This is a spring FactoryBean that creates an EntityManagerFactory. However, this factory is managed by spring. Instead of persistence.xml the configuration settings can be set in the spring application context. For example, create a datasource and pass the datasource in the LocalContainerManagedFactoryBean bean. If a data source is specified in both persistence.xml and in the spring configuration then the later takes precedence. Along with DataSource a property called jpaVendorAdapter is passed to the LocalContainerManagedFactoryBean. Different adapters such as HibernateJpaVendorAdapter, OpenJpaVendorAdapter etc are provided by spring. Various properties can be set in the Vendor Adapter. LocalContainerManagedFactoryBean is the mostly likely choice for use in spring.

Once an EntityManager is obtained, it can be injected into the DAO. The standard way is to use a JpaTemplate and a JpaDaoSupport, however to decrease coupling it is favorable to use pure JPA by directly injecting the EntityManager in the DAO. This can be achieved by using the @PersistenceContext annotation on the EntityManager variable in the DAO. The class is also annotated with @Repository so that spring knows that the exceptions need to be translated and with @Transactional to specify the transactional context.

Sample Program Overview

The sample program demonstrates the Spring, JPA and Hibernate integration.

We will create the Person class with members as id,name and email.

We will create the PersonDao class with members as SELECT_QUERY and entityManager.

We will create the PersonService class with members as personDao.

We will create the DbUtil class with members as dataSource.

We will also create the spring-config.xml.

Finally, we will test our setup using TestSpringHibernateSessionFactory class which will load Spring context and get a reference to PersonService class. We will add a person using the PersonService class and obtain a list of all Persons added.

Required Libraries
  • antlr-3.4-complete.jar
  • aopalliance.jar
  • cglib.jar
  • commons-collections.jar
  • commons-logging.jar
  • dom4j.jar
  • hibernate-annotations-3.4.0.GA.jar
  • hibernate-commons-annotations-3.3.0.ga.jar
  • hibernate-entitymanager-3.4.0.GA.jar
  • hibernate3.jar
  • hsqldb.jar
  • javaee-api-5.0-2.jar
  • javassist-3.8.0.GA.jar
  • jta-1.1.jar
  • log4j-1.2.16.jar
  • org.springframework.aop.jar
  • org.springframework.asm.jar
  • org.springframework.beans.jar
  • org.springframework.context.jar
  • org.springframework.context.support.jar
  • org.springframework.core.jar
  • org.springframework.expression.jar
  • org.springframework.jdbc.jar
  • org.springframework.orm.jar
  • org.springframework.transaction.jar
  • slf4j-api-1.6.1.jar
  • slf4j-log4j12-1.6.1.jar



Source Code

Create the Person (see sample code below). This is the entity which is inserted and selected from database using Hibernate.

Hibernate based mapping is done using annotations
@Entity
and
@Table
which tells Hibernate which table to map this entity to (see lines 9-10 below).

The mapping of identifier is done using annotations
@Id
,
@GeneratedValue
and
@Column
(see lines 16-18 below). This corresponds to the primary key of the PERSON table.

This demonstrates the usage of JPA annotations for
Object Relational Mapping
.

Create PersonDao class (see sample code below) which represents the
Data Access Object
which will interact with the database.

This class is annotated using JPA annotation
@Repository
annotation which tells Spring framework to load this class into its container (see line 14 below).

Use JPA annotation
@Transactional
to define that transactions need to be used (see line 15 below). Also note
propagation = Propagation.REQUIRED
which defines the transaction propagation is required.

Use the
@PersistenceContext
annotation which tells Spring to inject an instance of
EntityManager
into PersonDao (see line 20 below).

The insert() method inserts a Person object into database (see lines 31-33 below). It uses JPA class
EntityManager
to insert the Person object into database (see line 32 below)

Similarly, a list of all Persons is fetched from database using the
selectAll()
method (see lines 35-39 below). It uses JPA class
EntityManager
to create the query and select all persons from database (see lines 36-37 below).

The query to fetch all the persons is based on JPA’s object querying capabilitites (see line 18 below).

This demonstrates the usage of JPA’s
EntityManager
class to interact with the database.

Create PersonService class (see sample code below), a
Service
class which contains reference to PersonDao (see line 9 below). It is annotated using the
@Component
annotation to let Spring load it within its container (see line 8 below).

Note that
@Autowired
annotation is used to inject PersonDao (see line 16 below).

Create addPerson() and fetchAllPersons() methods which delegate the call to PersonDao (see lines 21-27 below).

Create the DbUtil (see sample code below). This class used only to create the necessary PERSON table in the database.

Create members dataSource (see line 11 below)

Create accessor methods for dataSource (see lines 13-19 below).

Create the initialize method and execute the ‘CREATE TABLE’ statement to create the PERSON table (see lines 21-32)

Create the persistence.xml file (see below) which is part of JPA’s specification.

Store this file META-INF directory in the classpath.

Declare the persistence unit for this application (see line 4 below).

Mention the class that should be used for persistence. In this case, the Person class is used for persistence (see line 5 below)

Create the spring-config.xml file (see below).

Declare the
context:component-scan
and specify the package from which Spring will load the classes based on their annotations (see line 14 below).

The dependency injection chart for the spring-config is as follows:

Note the
LocalContainerEntityManagerFactoryBean
class which is the JPA entity manager for container managed persistence (see lines 16-23 below). Also note that the persistence unit name ‘personPersistenceUnit’ matches in name with the declaration in persistence.xml (listed above)

JPA Adapter for Hibernate is specified in lines 25-29 below.

JPA dialect for Hibernate is specified in line 31 below.

The transaction manager to be used for JPA persistence is specified in lines 33-37 below.

We tell Spring to use annotation driven transaction management (see line 39 below).

The database parameters defined for dataSource bean (see lines 41-47 below) correspond to the HyperSQL in-memory database

We also declare the dbUtil bean which initializes the database by creating the PERSON table with ID, NAME and EMAIL columns (see lines 49-52 below).


Finally, we need a java program to test our setup.This is done by TestSpringHibernateJpa (see source code below).

We need to tell Spring framework to use the ‘spring-config.xml’ to load our beans (see line 13 below).

We get the reference to PersonService class through Spring using the bean name ‘personService’ (see line 14 below).

Create the Person object and set the name and email properties (see lines 16-18 below).

Use the PersonService.addPerson() method to add the Person object (see line 19 below).

Use the PersonService.fetchAllPersons() method to list the Persons added to the database (see line 22 below). We access the list of Persons and print the output to verify that database operations of inserting and selecting using JPA annotations for Hibernate based mapping within Spring framework have occured successfully (see line 23 below).


Running Sample Program

This sample program has been packaged as a jar installer which will copy the source code (along with all necessary dependencies) on your machine and automatically run the program for you as shown in the steps below. To run the sample program, you only need Java Runtime Environment (JRE) on your machine and nothing else.

Download And Automatically Run Sample Program
  • Save the springhibernatejpa-installer.jar on your machine
  • Execute/Run the jar using Java Runtime Environment


  • (Alternatively you can go the folder containing the springhibernatejpa-installer.jar and execute the jar using
    java -jar springhibernatejpa-installer.jar
    command)

  • You will see a wizard as shown below
  • Enter the location of the directory where you want the program to install and run (say, C:\Temp)
  • The installer will copy the program on your machine and automatically execute it. The expected output indicating that the program has run successfully on your machine is shown in the image below.
  • Browsing the Program

    This source code for this program is downloaded in the folder specified by you (say, C:\Temp) as an eclipse project called
    springhibernatejpa
    . All the required libraries have also been downloaded and placed in the same location. You can open this project from Eclipe IDE and directly browse the source code. See below for details of the project structure.

    1 thought on “Spring Hibernate Integration Using Java Persistence API”

    Leave a Comment