trainingtrains Logo

91-9990449935

 0120-4256464

Spring Data JPA Tutorial

Spring Data JPA API provides JpaTemplate class to integrate spring application with JPA.

JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise application. It is currently used as the replacement for complex entity beans.

The implementation of JPA specification are provided by many vendors such as:

  • Hibernate
  • Toplink
  • iBatis
  • OpenJPA etc.

Advantage of Spring JpaTemplate

You don't need to write the before and after code for persisting, updating, deleting or searching object such as creating Persistence instance, creating EntityManagerFactory instance, creating EntityTransaction instance, creating EntityManager instance, commiting EntityTransaction instance and closing EntityManager.

So, it save a lot of code.


In this example, we are going to use hibernate for the implementation of JPA.


Example of Spring and JPA Integration

Let's see the simple steps to integration spring application with JPA:

  1. create Account.java file
  2. create Account.xml file
  3. create AccountDao.java file
  4. create persistence.xml file
  5. create applicationContext.xml file
  6. create AccountsClient.java file

In this example, we are going to integrate the hibernate application with spring. Let's see the directory structure of jpa example with spring.

spring jpa example with directory structure
1) Account.java

It is a simple POJO class.


2) Account.xml

This mapping file contains all the information of the persistent class.


3) AccountDao.java

4) persistence.xml

5) applicationContext.xml

The generateDdl property will create the table automatically.

The showSql property will show the sql query on console.


6) Accountsclient.java

Output

Hibernate: insert into account100 (balance, owner, accountnumber) values (?, ?, ?)
Hibernate: insert into account100 (balance, owner, accountnumber) values (?, ?, ?)
Accounts created