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:
- create Account.java file
- create Account.xml file
- create AccountDao.java file
- create persistence.xml file
- create applicationContext.xml file
- 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.
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