Spring Boot

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 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.

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

CrudRepository
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.

JpaRepository
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.

PagingAndSortingRepository
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">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.dineshonjava.sdjpa</groupId>
 <artifactId>SpringBootJPASpringData</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

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

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.0.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <!-- <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
  </dependency> -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>


</project>
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
 *
 */
@Entity
@Table(name = "BOOKING")
public class Booking implements Serializable{

 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 Long bookingId;
 @Column
 String psngrName;
 @Column
 String departure;
 @Column
 String destination;
 @Column
 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;

@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
 *
 */
@RestController
@RequestMapping("/booking")
public class BookingController {
 
 @Autowired
 BookingRepository bookingRepository;
 /**
  * GET /create  --> Create a new booking and save it in the database.
  */
 @RequestMapping("/create")
 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.
  */
 @RequestMapping("/read")
 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.
  */
 @RequestMapping("/update")
 public Booking update(@RequestParam Long bookingId, @RequestParam String psngrName) {
  Booking booking = bookingRepository.findOne(bookingId);
  booking.setPsngrName(psngrName);
  booking = bookingRepository.save(booking);
     return booking;
 }
 
 /**
  * GET /delete  --> Delete a booking from the database.
  */
 @RequestMapping("/delete")
 public String delete(@RequestParam Long bookingId) {
  bookingRepository.delete(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;

@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
Summary
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!!!

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago