Spring Data JPA

 

Spring Data JPA is not a JPA provider but is a specification. It is a library / framework that adds an extra layer of abstraction on the top of our JPA provider. It simply “hides” the Java Persistence API (and the JPA provider) behind its repository abstraction.

JPA is the sun specification for persisting objects in the enterprise application. It is used as replacement for complex entity beans.

The implementation of JPA specification are provided by many JPA provider such as: Hibernate, Toplink, iBatis, OpenJPA etc.

Features provided by Spring Data JPA :

  • Create and support repositories created with Spring and JPA
  • Support JPA queries
  • Support for batch loading, sorting, dynamical queries
  • Supports XML mapping for entities
  • Reduce code size for generic CRUD operations by using CrudRepository

What Components Do We Need?

  • The JDBC driver which enables java application to interact with the database.
  • The datasource provides all technical information needed to access data.
  • The JPA Provider implements the Java Persistence API. We use Hibernate because it is the most common JPA provider.
  • Spring Data JPA hides the used JPA provider behind its repository abstraction.

The Java Persistence API is used for managing, persisting and accessing data between objects and relation database. Hibernate is an ORM (Object Relational Mapping) tool which implements JPA specification.

Following program illustrates how to integrate Spring with JPA, using the Hibernate as a JPA provider :

Exploring the Directory Structure :

Directory Structure

pom.xml file : Adding Spring, Hibernate and MySQL dependencies in maven project as follows:

JPA Entity class :  This is entity class Person consists of getter and setter methods.

Data Access Object (DAO) class :

PersonDao.java : This repository interface consists of methods to be implemented by implementation class.

PersonDaoImp.java : This repository class implements PersonDao interface to provide method body accordingly as to persist data in database.

Service class :

PersonService.java : This interface consists of methods to be implemented by implementation class at service layer.

PersonServiceImp.java : This service class implements PersonService interface to provide method body accordingly to our business logic.

persistence.xml file : This xml file contains information to connect with database.

Spring configuration :  This is configuration class with @EnableTransactionManagement annotation to enable transaction management capability.

Run application : This is main class to run the application.

Output : We will get the following output on console.

You can download this example : SPRING DATA JPA EXAMPLE

Leave a Reply