English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Spring Boot JPA is a Java specification used in Java applications for managementrelationshipdata. It allows us to access and persist Java objects/data between Java classes and relational databases. JPA followsObject-Relational Mapping(ORM). It is a set of interfaces. It also provides runtime EntityManager API for handling queries and transactions against database objects. It uses a platform-independent object-oriented query language JPQL (Java Persistence Query Language).
In terms of persistence, it covers three domains:
Java Persistence API Object-Relationalmetadatain persistence The API defined in the package itself
JPA is not a framework. It defines concepts that can be implemented in any framework.
Compared to JDBC, JPA is simpler, cleaner, and less labor-intensive, with SQL and handwritten mapping. JPA is suitable for complex applications that are not performance-oriented. Compared to JDBC, the main advantage of JPA is that in JPA, data is represented by objects and classes, while in JDBC, data is represented by tables and records. It uses POJO to represent persistent data, thus simplifying database programming. JPA also has other advantages:
JPA avoids using the database-specific dialect of SQL for DDL. Instead, it allows mapping to be done in XML or using Java annotations. JPA allows us to avoid writing DML using the database-specific dialect of SQL. JPA allows us to save and load Java objects and graphs without using any DML language at all.When we need to execute a JPQL query, it allows us to express the query using Java entities instead of (native) SQL tables and columns.
JPA has the following features:
This is a powerful repository and customobject mapping abstraction. It supportsCross-store persistence. This means that an entity can be partially stored in MySQL and Neo4in j(graph database management system).It dynamically generates queries from the query method name.Domain base class provides basic properties.It supports transparent auditing.The possibility of integrating custom repository code.It can be easily integrated with Spring Framework through custom namespaces.
JPA is the source that stores business entities as relational entities. It shows how to define POJO as an entity and how to manage entities through relationships.
The following figure describes the class-level architecture of JPA, which describes the core classes and interfaces of JPA. javax persistencePackage. The JPA architecture includes the following units:
Persistence: This is a class that contains static methods for obtaining EntityManagerFactory instances. EntityManagerFactory: It is the factory class for EntityManager. It creates and manages multiple instances of EntityManager. EntityManager: It is an interface. It controls the persistence operations on objects. It is applicable to Query instances. @Entity marks: Entities are persistent objects stored in the database as records. Persistence Unit: . It defines a set of all entity classes. In the application, the EntityManager instance manages them. A set of entity classes represents the data contained in a single data store. EntityTransaction: . It hasOne-to-oneRelationship. For each EntityManager, operations are maintained by the EntityTransaction class. Query: This interface is implemented by each JPA vendor to obtain relationship objects that meet the criteria.
The classes and interfaces we discussed above maintain a relationship. The following figure shows the relationship between classes and interfaces.
The relationship between EntityManager and EntiyTransaction isOne-to-one. Each EntityManager operation has an EntityTransaction instance. The relationship between EntityManageFactory and EntiyManager isOne-to-many. This is the factory class of EntityManager instance. The relationship between EntityManager and Query isOne-to-many. We can use the instance of EntityManager class to execute any number of queries. The relationship between EntityManager and Entity isOne-to-many. The EntityManager instance can manage multiple entities.
JPA is an open-source API. There are various enterprise vendors, such as Eclipse, RedHat, Oracle, etc., that provide new products by adding JPA. There are some popular JPA implementation frameworks, such as Hibernate, EclipseLink, DataNucleus etc. It is also known asObject-Relational Mapping(ORM) tools.
In ORM, the mapping of Java objects to database tables (and vice versa) is calledObject-Relational Mapping (ORM). ORM mapping acts asrelational databaseand (tables and records), and Java applicationA bridge between (classes and objects).
As shown in the figure below, the ORM layer is the adapter layer. It adapts the language of the object graph to the language of SQL and relational tables.
The ORM layer exists between the application and the database. It converts Java classes and objects so that they can be stored and managed in relational databases. By default, the name of the persistence will become the name of the table, and the fields will become columns. Once the application is established, each table row corresponds to an object.
Early versions of EJB defined a persistence layer integrated with the business logic layer. It uses javax.ejb.EntityBean interface. The EJB specification includes the definition of JPA.
with the introduction of EJB 3.0, the persistence layer was separated and specified as JPA 1.0 (Java Persistence API). The specification of this API has been released with2006Year5Month11Day use JSR 220 of JAVA EE5specification and released together.
2019in the year, JPA was renamed to Jakarta Persistence . The latest version of JPA is 2.2 . It supports the following features:
Java 8and data and time API AttributeConvertes with CDI injectionIt makes the annotation @Repeatable
JPA: JPA is a Java specification for accessing, managing, and persisting Java objects and relational databases. This is the standard method for ORM.
Hibernate: It is a lightweight open-source ORM tool used to store Java objects in relational database systems. It is a provider of JPA. It follows a general method provided by JPA.
The following table describes the differences between JPA and Hibernate.
JPA | Hibernate |
JPA is used to map relational data in Java applications Java specification. | Hibernate is a Java specification for handling data persistence ORM framework. |
JPA does not provide any implementation classes. | It provides implementation classes. |
It uses a called JPQL (Java Persistence Query Language). | It uses its own platform-independent query language called HQL query language (Hibernate query language). |
It is defined in javax.persistence package. | It is defined in org.hibernate package. |
It is defined in Hibernate, EclipseLink and various ORM tools. | Hibernate is an implementation of JPAprovider. |
JPA uses EntityManager to handle data persistence. | In Hibernate, use Session to handle data persistence. |
Spring Boot provides starter dependencies spring-boot-starter-data-JPA to efficiently use relational databases to connect with Spring Boot applications. spring-boot-starter-data-JPA internally uses spring-boot-JPA dependencies.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.2.2.RELEASE</version> </dependency>
We create a Spring Boot application that connects to the database using JPA. In the following example, we use an in-memory database Apache Derby.
Apache Derby : This is an embeddedOpen source softwareA relational database fully implemented in Java. It is licensed under the Apache License 2Available under .0. Apache Derby has the following advantages:
Easy to install, deploy, and use.It is based on Java, JDBC, and SQL standards.It provides an embedded JDBC driver that allows us to embed Derby into any Java-based solution.It also supports clients through the Derby Network Client JDBC driver and Derby Network Server./server mode.
Spring Boot can automatically configure embedded databases, such as H2, HSQL,and Derbydatabases . We do not need to provide any connection URL. We just need to include the build dependency of the embedded database we want to use.
In Spring Boot, you just need to add in the pom. Derby dependency to easily integrate Apache Derby database. xml file.
<dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <scope>runtime</scope> </dependency>
Steps1: Open Spring Initializr https://start.spring.io/.
Steps2: Select the latest version of Spring Boot 2.3.0(SNAPSHOT)
Steps3: provideGroupName. We have provided com.w3codebox.
Steps4: provideArtifact ID. We provide apache-derby-example .
Steps5: Add dependencies: Spring Web, Spring Data JPAand Apache Derby database.
Steps6: Click Generate (Generate) button. When we click the "Generate" button, it will package the project into a Jar file and download it to the local system.
Steps7: Extract Jar file and paste it into the STS workspace.
Steps8: Import
File->Import->Existing Maven project->Browse->Select folder apache-derby-example-Completed
It takes some time to import.
Steps9: in the folder src/main/javaCreate a name called com.w3codebox.model package.
Steps10: in the package com.w3codebox.model Create a name called UserRecord of the class, and then execute the following:
Define three variables id, name, and email.Generate Getter and Setter.
Right-click on the file-> Source-> Generate Getter and Setter Define the default constructor.Use annotations Entity marks the class as@Entity marks. Use annotations @Id marks Id Mark as primary key.
UserRecord.java
package com.w3codebox.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class UserRecord { @Id private int id; private String name; private String email; //default constructor public UserRecord() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
Steps11: in src/main/Create a folder named com.w3codebox.controller package.
Steps12: in the package com.w3codebox.controller Create a name called UserController Controller class, and perform the following operations:
Use annotations @RestController Mark the class as a controller.Use annotations @Autowired Automatically connect class UserService .We define two mappings, one mapping is used forRetrieve all users, another mapping is used forAdd user.
UserController.java
package com.w3codebox.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.w3codebox.model.UserRecord; import com.w3codebox.service.UserService; import java.util.List; @RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/") public List<UserRecord> getAllUser() { return userService.getAllUsers(); } @RequestMapping(value="/add-user, method=RequestMethod.POST) public void addUser(@RequestBody UserRecord userRecord) { userService.addUser(userRecord); } }
Steps13: in the folder src/main/Create a named in Java com.w3codebox.service package.
Steps14: in the package com.w3codebox.service Create a name called UserController of the Service class, and perform the following operations:
By using annotations @ServiceMark this class as a service. Automatic connection UserRepository Define a method getAllUsers()which returns the following list: Define another method name addUser()to save user records.
UserService.java
package com.w3codebox.service; import java.util.List; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.w3codebox.model.UserRecord; import com.w3codebox.repository.UserRepository; @Service public class UserService { @Autowired private UserRepository userRepository; public List<UserRecord> getAllUsers() { List<UserRecord> userRecords = new ArrayList<>(); userRepository.findAll().forEach(userRecords::add); return userRecords; } public void addUser(UserRecord userRecord) { userRepository.save(userRecord); } }
Steps15: in the folder src/main/javaCreate a name called com.w3codebox.repository package.
Steps16: in the package com.w3codebox.repository Create a name called UserRepository the repository interface, and extends CrudRepository .
UserRepository.java
package com.w3codebox.repository; import org.springframework.data.repository.CrudRepository; import com.w3codebox.model.UserRecord; public interface UserRepository extends CrudRepository<UserRecord, String> { }
Steps17: Now, open ApacheDerbyExampleApplication.java file. It is the default one created when we set up the application.
ApacheDerbyExampleApplication.java
package com.w3codebox; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ApacheDerbyExampleApplication { public static void main(String[] args) { SpringApplication.run(ApacheDerbyExampleApplication.class, args); } }
Now, we have set up all the necessary classes and packages as required. Please note that we have not provided any for the database.Connection URL . After completing all the above steps, the project directory will look like this:
Let's run the application.
Steps18: Open ApacheDerbyExampleApplication.java File and run it as a Java application.
第19Step: Open the browser and call the URL http://localhost:8080/。Since no users were added to the list, an empty list is returned.
To add a user to the database, we will useSend POST Request Postman.
Steps20: OpenPostman,然后执行以下操作:
Select POST Call URL http://localhost:8080/add-user.ClickBody Select Content-Type asJSON (application/json).Insert the data to be inserted into the database. We have inserted the following data:
{ "id": "00"1", "name": "Tom", "email": "[email protected]" }
ClickSendButton.
It displays when we click the "Send" buttonStatus: 200 OK . This indicates that the request has been executed successfully.
Steps21: Open the browser and call the URL http: //localhost: 8080. It returns the users we have inserted into the database.