Spring Data JPA using Spring Boot Application

Hello friends !!! In this tutorial we are going to discuss how to use and configure Spring Data JPA with Spring Boot Application with minimal configuration as always with Spring Boot. Spring Data JPA and Hibernate (as JPA implementation) will be used to implement the data access layer.
Spring Data?
Spring Data is a high level project developed by Spring community aimed at simplifying the data access operations for the applications. If you are using Spring Data in your project, you are not going to write most of the low level data access operations like writing SQL query DAO classes etc. Spring Data will generate everything dynamically at run-time by creating the proxy instances of your abstract repositories and perform the required operations.

There are several sub projects provided by Spring Data like Spring Data JPA, Spring Data Solr, Spring Data MongoDB, Spring Data REST etc. Here we are going to discuss one of them Spring Data JPA.

Spring Data JPA?
The Spring Data JPA is the implementation of JPA for simplifying operation like data accessing, querying, pagination and removes lots of boilerplate codes. The Java Persistence API is a standard technology that allows you to ‘map’ objects to relational databases. The spring-boot-starter-data-jpa POM provides a quick way to get started. It provides the following key dependencies:

  • Hibernate — One of the most popular JPA implementations.
  • Spring Data JPA — Makes it easy to implement JPA-based repositories.
  • Spring ORMs — Core ORM support from the Spring Framework

Spring Data Repositories
Spring data provides the abstract repositories, which are implemented at run-time by the spring container and perform the CRUD operations. As a developer we have to just provide the abstract methods in the interface. This reduces the amount of boilerplate code required to write data access layers. There are following are base interfaces providing by Spring Data.

It is the central interface in the spring data repository abstraction. This is a marker interface.

CrudRepository provides methods for the CRUD operations. This interface extends the Repository interface. If you are extending the CrudRepository, there is no need for implementing your own methods. Just extend this interface and leave it as blank.

This is the special version of CrudRepository specific to the JPA technology. Recommended to use CrudRepository because it will not tie your application with any specific store implementations.

It is specialized version for the paging operations and extension of CrudRepository.

Spring Data JPA and Spring Boot Application
Here I am going make at REST API application for providing the booking information of train ticket and also we can the book the train ticket using API. Here I am using MySQL database in a Spring Boot web application, using less code and configurations as possible. First we have to create the project so I am using here Spring Boot Web Initializr for creating project with selecting maven build and required dependencies for this project like WEB, SPRING DATA JPA, and MYSQL. Now let’s see required part of the maven file for this project.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


 <description>SpringBootJPASpringData project for Spring Boot with Spring Data JPA implementation</description>

  <relativePath/> <!-- lookup parent from repository -->



  <!-- <dependency>
  </dependency> -->



If you look at the above maven dependencies.
  • spring-boot-starter-data-jpa dependency will download the files required for spring data jpa.
  • spring-boot-starter-web is required because it is web based application to expose the REST endpoints.
  • mysql-connector-java dependency will download the files required for mysql database.

Configuration file application.properties
# DataSource settings: set here your own configurations for the database 
# connection. In this example we have "dojsb" as database name and 
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:3307/dojdb
spring.datasource.username = root
spring.datasource.password = root

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = create

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

server.port = 8181

Using hibernate configuration ddl-auto = update the database schema will be automatically created (and updated), creating tables and columns, accordingly to java entities found in the project. For this application I am using server port is 8181.

Entity file Booking.java
Create an entity class representing a table in your db. Here I am using Booking.java as entity files which map to the booking table in the database dojdb.

package com.dineshonjava.sdjpa.models;

import java.io.Serializable;
import java.util.Date;

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

 * @author Dinesh.Rajput
@Table(name = "BOOKING")
public class Booking implements Serializable{

 private static final long serialVersionUID = 1L;
 @GeneratedValue(strategy = GenerationType.AUTO)
 Long bookingId;
 String psngrName;
 String departure;
 String destination;
 Date travelDate;

 public Long getBookingId() {
  return bookingId;

 public void setBookingId(Long bookingId) {
  this.bookingId = bookingId;

 public String getPsngrName() {
  return psngrName;

 public void setPsngrName(String psngrName) {
  this.psngrName = psngrName;

 public String getDeparture() {
  return departure;

 public void setDeparture(String departure) {
  this.departure = departure;

 public String getDestination() {
  return destination;

 public void setDestination(String destination) {
  this.destination = destination;

 public Date getTravelDate() {
  return travelDate;

 public void setTravelDate(Date travelDate) {
  this.travelDate = travelDate;

The @Entity annotation marks this class as a JPA entity. The @Table annotation specifies the db table’s name.

The Data Access Object (Repository): BookingRepository.java
Repository is needed to works with entities in database’s table, with methods like save, delete, update, etc. With Spring Data JPA a DAO for your entity is simply created by extending the CrudRepository interface provided by Spring. The following methods are some of the ones available from such interface: save, delete, deleteAll, findOne and findAll.

package com.dineshonjava.sdjpa.models;

import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;

public interface BookingRepository extends CrudRepository {
    * This method will find an Boooking instance in the database by its departure.
    * Note that this method is not implemented and its working code will be
    * automatically generated from its signature by Spring Data JPA.
   public Booking findByDeparture(String departure);

Adding Rest Controller BookingController.java
Here adding one more file for accessing Rest APIs is RestController it provide me some URLs for CRUD operation the booking table.

package com.dineshonjava.sdjpa.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dineshonjava.sdjpa.models.Booking;
import com.dineshonjava.sdjpa.models.BookingRepository;

 * @author Dinesh.Rajput
public class BookingController {
 BookingRepository bookingRepository;
  * GET /create  --> Create a new booking and save it in the database.
 public Booking create(Booking booking) {
  booking.setTravelDate(new Date());
  booking = bookingRepository.save(booking);
     return booking;
  * GET /read  --> Read a booking by booking id from the database.
 public Booking read(@RequestParam Long bookingId) {
  Booking booking = bookingRepository.findOne(bookingId);
     return booking;
  * GET /update  --> Update a booking record and save it in the database.
 public Booking update(@RequestParam Long bookingId, @RequestParam String psngrName) {
  Booking booking = bookingRepository.findOne(bookingId);
  booking = bookingRepository.save(booking);
     return booking;
  * GET /delete  --> Delete a booking from the database.
 public String delete(@RequestParam Long bookingId) {
     return "booking #"+bookingId+" deleted successfully";

That’s all! The connection with the database is done when we run the following file as Java Application or Spring Boot application.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class SpringBootJpaSpringDataApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootJpaSpringDataApplication.class, args);
Project Structure:

Test the controller launching the Spring Boot web application and using these urls:

Creating New Record:
/booking/create?psngrName=Dinesh&departure=Noida&destination=Pune create a new booking with an auto-generated.
For Example:
• bookingId: 4,
• psngrName: "Arnav",
• departure: "Delhi",
• destination: "USA",
• travelDate: 1470828738680

Reading a Record:
/booking/read?bookingId=[bookingId]: Read the booking with the passed bookingId.

For Example:

• bookingId: 1,
• psngrName: "Dinesh",
• departure: "Noida",
• destination: "Pune",
• travelDate: 1470828563000
Updating a Record:
/booking/update?bookingId=[bookingId]&psngrName=Sweety: Update the booking for a given booking id.

For Example:
• bookingId: 5,
• psngrName: "Suresh",
• departure: "Agra",
• destination: "Noida",
• travelDate: 1470828994000
Deleting a Record:
/booking/delete? bookingId=[bookingId]: Delete a booking for given booking id.

For Example:
booking #5 deleted successfully

In this chapter I have explained how to use Spring Data JPA and Spring Boot frameworks. Also explained in short about the Spring Data Repositories and query methods.

Happy Spring Boot Learning!!!

No comments:

Post a Comment