Using Hibernate JPA in Spring

JPA (Java Persistence API) provides a good ORM (Objet Relational Mapper) solution. It has a large success because it’sa standard and it’s implemented by different vendor.

Hibernate Implements JPA specification. Using this implementation has the benefit of avoiding hbm.xml mapping files and to use annotations metatdata to specify the mapping between objects and relational database tables.

This article will show by a project example how to persist data with Hibernate JPA implementation and Spring Framework.

Photo Credit : tanakawho

The picture bellow presents the project structure and the different files created. If you are using maven you need to add dependency as shown in the picture, otherwise you have to download jars from Springsource and Hibernate web sites and to manage dependencies.


1 – Hibernate JPA configuration
The JPA interface needs a configuration file named persistence.xml in the application’s META-INF directory. The sourcecode bellow present the persistence.xml file used in this project.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="" 
    <persistence-unit name="acme" transaction-type="RESOURCE_LOCAL">
            <property name="" value="create-drop"/>

JPA persist a simple POJO Classe with some metatdata wich are specified in annotations. For more information about JPA annottion, see Chapter 8 “Metadata Annotations” of the JPA Specification . Here is an example data class:

import java.util.List;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;

@Table(name = "Customer")
public class Customer implements Serializable {

    public Customer() {super();}

public Customer(Integer taxId, String name, String adresse, String city, 
String state, String zip, String phone, List<CustomerOrder> CustomerOrders) {
        this.taxId = taxId; = name;
        this.adresse = adresse; = city;
        this.state = state; = zip; = phone;
        this.CustomerOrders = CustomerOrders;

    @GenericGenerator(name = "generator", strategy = "increment")
    @GeneratedValue(generator = "generator")
    @Column(name = "customer_id", nullable = false)
    private Long customerId;

    @Column(name = "tax_id", nullable = false)
    private Integer taxId;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "adresse", nullable = false)
    private String adresse;

    @Column(name = "city", nullable = false)
    private String city;

    @Column(name = "state", nullable = false)
    private String state;

    @Column(name = "zip", nullable = false)
    private String zip;

    @Column(name = "phone", nullable = false)
    private String phone;

    private List<CustomerOrder> CustomerOrders;

    // Add getters and setters

2 – Using JPA in Spring
In this part we explain how to integrate Hibernate JPA implementation into Spring.
The source code bellow present the application context used to configure Hibernate JPA into Spring Framework.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""


    <context:component-scan base-package="com.mycompany"/>

    <bean id="entityManagerFactory"
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceXmlLocation" value="persistence.xml"  />
        <property name="jpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />

    <bean id="dataSource"
        <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
        <property name="url" value="jdbc:hsqldb:mem:test" />
        <property name="username" value="sa" />
        <property name="password" value="" />

	<tx:annotation-driven />
    <bean id="transactionManager"
     class="org.springframework.orm.jpa.JpaTransactionManager" >
        <property name="entityManagerFactory" ref="entityManagerFactory"  />


The code source bellow present the customer DAO.

package com.mycompany.dao.hibernate;

import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.mycompany.dao.ICustomerDao;
import com.mycompany.entity.Customer;

public class CustomerDao implements ICustomerDao{
	private EntityManager em;

    public Collection<Customer> getAll() {
    	Query query = em.createQuery("from Customer");
        return query.getResultList();
    public Collection<Customer> findByName(String name) {
    	Query query = em.createQuery("from Customer as c where like :name");
    	query.setParameter("name", name);
        return query.getResultList();

    public Customer getById(Long id) {
        return em.find(Customer.class, id);

    public void save(Customer customer) {

    public void delete(Long id) {
    	Customer customer = em.find(Customer.class, id);  

4 thoughts on “Using Hibernate JPA in Spring

  1. I think this code is not at all using JPA as JPA is not mapped to any classes. Ideally JPA entitymanagerfactory should be injected to all dao classes and the ref should be used inside the class.

    • Thank you for your comment.

      I tried to look for documentations and articles about HibernateTemplate. You can find one of them in this link :

      I think that this poject uses JPA. But, you are right, this is not the more recommended way to use it in a Spring project. But I think this solution still a good solution for developers who are familiar with Spring jdbcTemplate.

      I will try to update this article.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s