Over a million developers have joined DZone.

Using the Spring Data JPA

DZone's Guide to

Using the Spring Data JPA

Want to learn how to use the Spring Data JPA to replace complex entity beans? This tutorial explores the Spring Data JPA and how to use the directory structure.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Spring Data JPA is not a JPA provider but 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. Therefore, it is used as a replacement for complex entity beans.

The implementation of JPA specifications is provided by many JPA providers, 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 the CrudRepository

What Components Do We Need?

  • The JDBC driver enables Java applications to interact with the database.
  • The data source 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 the relational database. Hibernate is an ORM (Object Relational Mapping) tool that implements JPA specification.

The 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 : We will do this by adding Spring, Hibernate, and MySQL dependencies in the Maven project as shown below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"






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

package com.innovationM.spring.entity;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GenerationType;
import javax.persistence.Table;

@Table(name = "PERSONS")
public class Person {

   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @Column(name = "FIRST_NAME")
   private String firstName;

   @Column(name = "LAST_NAME")
   private String lastName;

   @Column(name = "EMAIL")
   private String email;

   public Person() {}

   public Person(String firstName, String lastName, String email) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.email = email;

   //getter and setter methods.

Data Access Object (DAO) Class 

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

package com.innovationM.spring.dao;

import java.util.List;

import com.innovationM.spring.entity.Person;

public interface PersonDao {
   void add(Person person);
   List<Person> listPersons();

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

package com.innovationM.spring.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.innovationM.spring.entity.Person;

public class PersonDaoImp implements PersonDao {

   private EntityManager em;

   public void add(Person person) {

   public List<Person> listPersons() {
      CriteriaQuery<Person> criteriaQuery = em.getCriteriaBuilder().createQuery(Person.class);
      Root<Person> root = criteriaQuery.from(Person.class);
      return em.createQuery(criteriaQuery).getResultList();


Service Class

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

package com.innovationM.spring.service;

import java.util.List;

import com.innovationM.spring.entity.Person;

public interface PersonService {
    void add(Person person);
    List<Person> listPersons();

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

package com.innovationM.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.innovationM.spring.dao.PersonDao;
import com.innovationM.spring.entity.Person;

public class PersonServiceImp implements PersonService {

   private PersonDao userDao;

   public void add(Person person) {

   @Transactional(readOnly = true)
   public List<Person> listPersons() {
      return userDao.listPersons();


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

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"

  <persistence-unit name="LOCAL_PERSISTENCE">
    <description> Spring Hibernate JPA Configuration Example</description>

      <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/demo" />
      <property name="javax.persistence.jdbc.user" value="root" />
      <property name="javax.persistence.jdbc.password" value="root" />
      <property name="hibernate.show_sql" value="true" />
      <property name="hibernate.hbm2ddl.auto" value="update" />


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

package com.innovationM.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@ComponentScans(value = { @ComponentScan("com.innovationM.spring.dao"),
      @ComponentScan("com.innovationM.spring.service") })
public class AppConfig {

   public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() {
      LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
      return factoryBean;

   public JpaTransactionManager geJpaTransactionManager() {
      JpaTransactionManager transactionManager = new JpaTransactionManager();
      return transactionManager;

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

package com.innovationM.spring;

import java.sql.SQLException;
import java.util.List;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.innovationM.spring.config.AppConfig;
import com.innovationM.spring.entity.Person;
import com.innovationM.spring.service.PersonService;

public class MainApp {
   public static void main(String[] args) throws SQLException {
      AnnotationConfigApplicationContext context = 
            new AnnotationConfigApplicationContext(AppConfig.class);

      PersonService personService = context.getBean(PersonService.class);

      // Add Persons
      personService.add(new Person("Rahul", "Gupta", "rahulgupta@company.com"));
      personService.add(new Person("Akshay", "Sharma", "akshaysharma@company.com"));
      personService.add(new Person("Ankit", "Sarraf", "ankitsarraf@company.com"));

      // Get Persons
      List<Person> persons = personService.listPersons();
      for (Person person : persons) {
         System.out.println("Id = "+person.getId());
         System.out.println("First Name = "+person.getFirstName());
         System.out.println("Last Name = "+person.getLastName());
         System.out.println("Email = "+person.getEmail());


Output: We will get the following output on the console.

Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: select person0_.id as id1_0_, person0_.EMAIL as EMAIL2_0_, person0_.FIRST_NAME as FIRST_NA3_0_, person0_.LAST_NAME as LAST_NAM4_0_ from PERSONS person0_
Id = 1
First Name = Rahul
Last Name = Gupta
Email = rahulgupta@company.com

Id = 2
First Name = Akshay
Last Name = Sharma
Email = akshaysharma@company.com

Id = 3
First Name = Ankit
Last Name = Sarraf
Email = ankitsarraf@company.com

You can download this example here.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

hibernate ,java ,jpa ,orm ,spring ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}