Simple Maven2, Spring 2.5, JPA and Hibernate integration

A few months ago, i’ve read a tutorial about spring 2.5 writen by Endy Muhardin (one of JUG Indonesia Hall Of Fame), that tutorial explained bout newest features of Spring 2.5, this version now supports Annotation. Configuration is no longer always in xml file. this made our effort to build program pragmatically  more easier to configure, faster and efficient.

But due to my bustle, and a regulation in place i work now. i have to leave Spring Frameworks. My project prefer choosing EJB3 and Struts2 as main developtment stack. the main reason is our client need a distributable application (even i know that spring support those too). Besides, developt a  ORM for handling database using JPA is more interesting for me than other approach. One question is, how bout people who doesnt need EJB feature which needed heavy container like Glassfish or JBOSS to running their application?.

Fortunately, Spring support JPA for connecting  to database, we can choose Hibernate or Toplink for JPA implementations. and it’s still can run in light web server like tomcat or jetty.  i’ll give you very simple example using JPA+Hibernate in Spring 2.5.

I’m using apache-maven2 for build this program, you can download it here and read this tutorial for installation.

Let me assume you have using maven2 before. Because we using Hibernate-Annotation, we need create a POJO class references from our table in database. All entity class must be registered with @Entity annotation. in Person class below i have added named query. it can be used if we want create costum query beside delete, update or persist (create) data.

package org.thenest.simplespring.models;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Table(name = "PERSON")
@NamedQueries( { @NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p") })
public class Person {
	private int id;
	private String name;
	private int age;

	public void setId(int id) { = id;

	public int getId() {
		return id;

	public void setName(String name) { = name;

	public String getName() {
		return name;

	public void setAge(int age) {
		this.age = age;

	public int getAge() {
		return age;

And this is DDL file for create table PERSON (i’m using mysql), and insert data into thus table.


INSERT INTO PERSON values(NULL,'Michael','22');
INSERT INTO PERSON values(NULL,'Alex','23');
INSERT INTO PERSON values(NULL,'Kevin','19');

One DAO class interface and it’s implementations. we can notice that PersonServiceJpa class have @Repository annotation. it’s mean we doesn’t needed to register this DAO class in Spring’s application context. We gonna make all DAO auto scanned.


import java.util.List;

import org.thenest.simplespring.models.Person;

public interface IPersonService {
	public boolean save(Person person);
	public List<Person> getAll();
	public Person getById(int id);
	public boolean delete(Person person);
	public boolean update(Person person);


import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.thenest.simplespring.models.Person;

@Transactional(readOnly = true)
public class PersonServiceJpa implements IPersonService {

	private EntityManager entityManager;

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

	public EntityManager getEntityManager() {
		return entityManager;

	public Person getById(int id) {
		// TODO Auto-generated method stub
		return entityManager.find(Person.class, id);

	public List<Person> getAll() {
		Query query = entityManager.createNamedQuery("Person.findAll");
		List&amp;lt;Person&amp;gt; persons = null;
		persons = query.getResultList();
		return persons;

	public boolean save(Person person) {
		return true;

	public boolean update(Person person) {
		return true;

	public boolean delete(Person person) {
		person = entityManager.getReference(Person.class, person.getId());
		if (person == null)
			return false;
		return true;

And persistence.xml file :

<persistence xmlns=""

	<persistence-unit name="testa" transaction-type="RESOURCE_LOCAL">

Here they are application context, you need to change dataSource setting with your locat variable.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
	xmlns:xsi="" xmlns:p=""
	xmlns:aop="" xmlns:context=""
	xmlns:jee="" xmlns:tx=""

	<context:annotation-config />
	<context:component-scan base-package="" />
	<tx:annotation-driven />
	<bean id="dataSource"
		p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost/iseng"
		p:username="root" p:password="rahasia" />
	<bean id="entityManagerFactory"
		p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
		<property name="loadTimeWeaver">
				class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
		p:entityManagerFactory-ref="entityManagerFactory" />
	<bean id="jpaAdapter"
		p:database="MYSQL" p:showSql="true" />

Cause i’m using JUnit too for unit testing, this is unit testing class. i assume you have using JUnit too before.


import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.thenest.simplespring.models.Person;

public class PersonDaoSpringJpaTest {

	private ApplicationContext ctx;
	private IPersonService personService;
	private Logger log = Logger.getLogger(this.getClass());

	public PersonDaoSpringJpaTest() {
		// TODO Auto-generated constructor stub
		ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		personService = (IPersonService) ctx.getBean("iPersonService");"Application Context Loaded");

	public void testGetAll() {"Test get all =================================");
		for (Person p : personService.getAll()) {"Name : " + p.getName() + " Age " + p.getAge());

	public void testSave() {"Test Save Data =================================");
		Person person = new Person();

	public void testGetDataById() {"Test get data by id ==========================");
		Person p = personService.getById(1);"Name : " + p.getName() + " Age " + p.getAge());


	public void testUpdateData() {"Test update data =============================");
		Person p = personService.getById(1);"Name : " + p.getName() + " Age " + p.getAge());


	public void testDeleteData() {"Test delete all ==============================");
		Person p = personService.getById(1);


And last, Maven 2 build file, pom.xml.

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

You can download all complete code here . If you wan’t to integrating Spring without JPA bridge, I’ve already short tutorial about Spring 3.0 and Hibernate here


About singgihpraditya

Gua cuma orang biasa, gak lebih , gak kurang. code maniac (i've been entrust all whole live just to make a good code)
This entry was posted in Java. Bookmark the permalink.

6 Responses to Simple Maven2, Spring 2.5, JPA and Hibernate integration

  1. Kasim says:

    That’s really what I want!

    Thank you very much for your kindly sharing!

  2. Kasim says:

    By the way, I suggest you can use dbunit and hibernate3 hbm3ddl to create datebase schema and inject data into the database using maven.

  3. singgihpraditya says:

    Hi Kasim
    Thanks for your suggestion, glad to help you

  4. McG says:

    The code above bombed on me at:
    personService = (IPersonService) ctx.getBean(“iPersonService”);

    It seems there is no such bean declared in the above spring config file.

  5. McG says:

    Ahh… it was a typo causing issue. Your code works fine…

  6. Pingback: Spring 3.0 and Hibernate tutorial (part 1) « Me and my chaotic life

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