TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Spring Boot Starter Data JPA

Spring Boot Starter Data JPA with Introduction, Features, Project, Starter Project Wizard, CLI, Application, Annotations, DM, Properties, Actuator, Thymeleaf View, JPA, JDBC etc

<< Back to SPRING

Spring Data JPA

Spring Data is a high-level Spring Source project. Its purpose is to unify and easy access to the different kinds of persistence stores, both relational database systems, and NoSQL data stores.

When we implement a new application, we should focus on the business logic instead of technical complexity and boilerplate code. That's why the Java Persistent API (JPA) specification and Spring Data JPA are extremely popular.

Spring Data JPA adds a layer on the top of JPA. It means, Spring Data JPA uses all features defined by JPA specification, especially the entity, association mappings, and JPA's query capabilities. Spring Data JPA adds its own features such as the no-code implementation of the repository pattern and the creation of database queries from the method name.

Spring Data JPA

Spring Data JPA handles most of the complexity of JDBC-based database access and ORM (Object Relational Mapping). It reduces the boilerplate code required by JPA. It makes the implementation of your persistence layer easier and faster.

Spring Data JPA aims to improve the implementation of data access layers by reducing the effort to the amount that is needed.

Spring Data JPA Features

There are three main features of Spring Data JPA are as follows:

  • No-code repository: It is the most popular persistence-related pattern. It enables us to implement our business code on a higher abstraction level.
  • Reduced boilerplate code: It provides the default implementation for each method by its repository interfaces. It means that there is no longer need to implement read and write operations.
  • Generated Queries: Another feature of Spring Data JPA is the generation of database queries based on the method name. If the query is not too complex, we need to define a method on our repository interface with the name that starts with findBy. After defining the method, Spring parses the method name and creates a query for it. For example:
public interface EmployeeRepository extends CrudRepository<Employee, Long> 
{
Employee findByName(String name);
}

In the above example, we extend the CrudRepository that uses two generics: Employee and Long. The Employee is the entity that is to be managed, and Long is the data type of primary key

Spring internally generates a JPQL (Java Persistence Query Language) query based on the method name. The query is derived from the method signature. It sets the bind parameter value, execute the query, and returns the result.

There are some other features are as follows:

  • It can integrate custom repository code.
  • It is a powerful repository and custom object-mapping abstraction.
  • It supports transparent auditing.
  • It implements a domain base class that provides basic properties.
  • It supports several modules such as Spring Data JPA, Spring Data MongoDB, Spring Data REST, Spring Data Cassandra, etc.

Spring Data Repository

Spring Data JPA provides three repositories are as follows:

  • CrudRepository: It offers standard create, read, update, and delete It contains method like findOne(), findAll(), save(), delete(), etc.
  • PagingAndSortingRepository: It extends the CrudRepository and adds the findAll methods. It allows us to sort and retrieve the data in a paginated way.
  • JpaRepository: It is a JPA specific repository It is defined in Spring Data Jpa. It extends the both repository CrudRepository and PagingAndSortingRepository. It adds the JPA-specific methods, like flush() to trigger a flush on the persistence context.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>

Spring Boot Starter Data JPA

Spring Boot provides spring-boot-starter-data-jpa dependency to connect Spring application with relational database efficiently. The spring-boot-starter-data-jpa internally uses the spring-boot-jpa dependency (since Spring Boot version 1.5.3).

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>

The databases are designed with tables/relations. Earlier approaches (JDBC) involved writing SQL queries.  In the JPA, we will store the data from objects into table and vice-versa. However, JPA evolved as a result of a different thought process.

Before JPA, ORM was the term more commonly used to refer to these frameworks. It is the reason Hibernate is called the ORM framework.

JPA allows us to map application classes to table in the database.

  • Entity Manager: Once we define the mapping, it handles all the interactions with the database.
  • JPQL (Java Persistence Query Language): It provides a way to write queries to execute searches against entities. It is different from the SQL queries. JPQL queries already understand the mapping that is defined between entities. We can add additional conditions if required.
  • Criteria API: It defines a Java-based API to execute searches against the database.

Hibernate vs. JPA

Hibernate is the implementation of JPA. It is the most popular ORM framework, while JPA is an API that defines the specification. Hibernate understands the mapping that we add between objects and tables. It ensures that data is retrieved/ stored from the database based on the mapping. It also provides additional features on the top of the JPA.

Spring Boot JPA Example

In this example, we will use spring-boot-starter-data-jpa dependency to create a connection with the H2 database.

Step 1: Open spring Initializr https://start.spring.io/.

Step 2: Provide the Group name. We have provided com.TheDeveloperBlog.

Step 3: Provide the Artifact Id. We have provided spring-boot-jpa-example.

Step 4: Add the dependencies: Spring Web, Spring Data JPA, and H2 Database.

Step 5: Click on the Generate button. When we click on the Generate button, it wraps the project in Jar file and downloads it to the local system.

Spring Boot Starter Data JPA

Step 6: Extract the Jar file and paste it into the STS workspace.

Step 7: Import the project folder into STS.

File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-jpa-example -> Finish

It takes some time to import.

Step 8: Create a package with the name com.TheDeveloperBlog.controller in the folder src/main/java.

Step 9: Create a Controller class with the name ControllerDemo in the package com.TheDeveloperBlog.controller.

ControllerDemo.java

package com.TheDeveloperBlog.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ControllerDemo 
{
@RequestMapping("/")
public String home()
{
return "home.jsp";
}
}

Step 10: Create another package with the name com.TheDeveloperBlog.model in the folder src/main/java.

Step 11: Create a class with the name User in the package com.TheDeveloperBlog.model.

User.java

package com.TheDeveloperBlog.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="userdata")
public class User 
{
@Id
private int id;
private String username;
public int getId() 
{
return id;
}
public void setId(int id) 
{
this.id = id;
}
public String getUname() 
{
return username;
}
public void setUname(String username) 
{
this.username = username;
}
@Override
public String toString() 
{
return "User [id=" + id + ", uname=" + username + "]";
}
}

Now we need to Configure the H2 database. 

Step 12: Open the application.properties file and configure the following things: port, enable the H2 console, datasource, and URL.

application.properties

server.port=8085
spring.h2.console.enabled=true
spring.datasource.plateform=h2
spring.datasource.url=jdbc:h2:mem:TheDeveloperBlog

Step 13: Create a SQL file in the folder src/main/resources.

Right-click on the folder src/main/resources -> New -> File -> Provide the File name -> Finish

We have provided the file name data.sql and insert the following data into it.

data.sql

insert into userdata values(101,'Tom');
insert into userdata values(102,'Andrew');
insert into userdata values(103,'Tony');
insert into userdata values(104,'Bob');
insert into userdata values(105,'Sam');

Step 14: Create a folder with the name webapp in the src folder.

Step 15: Create a JSP file with the name that we have returned in the ControllerDemo. In the ControllerDemo.java, we have returned home.jsp.

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="addUser">
ID :<br />
<input type="text" name="t1"><br />
User name :<br />
<input type="text" name="t2"><br />
<input type="submit" value="Add">
</form>
</body>
</html>

Step 16: Run the SpringBootJpaExampleApplication.java file. We can see in the console that our application is successfully running on port 8085.

Spring Boot Starter Data JPA

Step 17: Open the browser and invoke the URL http://localhost:8085/h2-console/. It shows the Driver Class, JDBC URL that we have configured in the application.properties file, and the default User Name sa.

Spring Boot Starter Data JPA

We can also test the connection by clicking on the Test Connection button. If the connection is successful, it shows a message Test Successful.

Step 18: Click on the Connect button. It shows the structure of the table userdata that we have defined in the User.java.

Spring Boot Starter Data JPA

Step 19: Execute the following query to see the data that we have inserted in the data.sql file.

SELECT * FROM USERDATA;

Spring Boot Starter Data JPA





Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf