English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Spring Data is an advanced Spring Source project. Its purpose is to unify and easily access different types of persistence storage, such as relational database systems and NoSQL data stores.
When implementing a new application, we should focus on business logic rather than technical complexity and boilerplate code. This is why the Java Persistence API (JPA) specification and Spring Data JPA are very popular.
Spring Data JPA adds a layer on top of JPA. This means that Spring Data JPA uses all the features defined by the JPA specification, especially entities, association mappings, and JPA's query capabilities. Spring Data JPA adds its own features, such as the no-code implementation of repository patterns and the creation of database queries from method names.
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.
Spring Data JPA aims to improve the implementation of the data access layer by reducing the amount of work required.
Spring Data JPA has threeMain features, as follows:
No-code repository: This is the most popular persistence-related pattern. It allows us to implement business code at a higher level of abstraction. Simplified boilerplate code: It provides a default implementation for each method through its repository interface. This means that there is no need to implement read and write operations. generated queries: Another feature of Spring Data JPA is that it generates queries based on method namesto generate database queries. If the query is not too complex, it is necessary to define a method with findBy methods starting with the name. 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 extended the use of two generics CrudRepository : Employee and Long . Employee is the one to be managed entity, and Long is the data type of the primary key
Spring internally generates JPQL (Java Persistence Query Language) Query based on method name. The query is derived from the method signature. It sets the binding parameter values, executes the query, and returns the results.
There are also other features, as shown below:
It can integrate custom repository code. This is a powerful repository and custom object mapping abstraction. It supports transparent auditing. It implements domain base classes that provide basic attributes. It supports multiple modules, such as Spring Data JPA, Spring Data MongoDB, Spring Data REST, Spring Data Cassandra, etc.
Spring Data JPA provides threerepositories, as shown below:
CrudRepository: : It provides standardcreate, read, updateanddelete. It includes such as findOne(), findAll(), save(), delete(),and so on. PagingAndSortingRepository It extends CrudRepository and adds the findAll method. It allows us to retrieve data in a paginated mannersortingandretrievaldata. JpaRepository : This is JPA-specific repositories, which is in Spring Data Jpa defined. It extends the repository CrudRepository and PagingAndSortingRepository. It adds JPA-specific methods such as flush(), to trigger a refresh on the persistence context.
<dependency> <groupId>org.springframework.data</<groupId> <artifactId>spring-data-jpa</artifactId> <version>2.2.3.RELEASE</version> </dependency>
Spring Boot provides spring-boot-starter-data-jpa dependencies to effectively connect Spring applications with relational databases. spring-boot-starter-data-jpa internally uses spring-boot-jpa dependency (since Spring Boot version1.5.3)).
<dependency> <groupId>org.springframework.boot</<groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.2.2.RELEASE</version> </dependency>
The database is used with tables/The relational design. The earlier methods (JDBC) involved writing SQL queries. In JPA, we will store data from objects to tables, and vice versa. However, JPA has evolved due to a different thought process.
Before JPA, ORM was the term more commonly used to refer to these frameworks. That's why Hibernate is called an ORM framework.
JPA allows us to map application classes to tables in the database.
Entity Manager: : After defining the mappings, it handles all interactions with the database. JPQL (Java Persistence Query Language): It provides a method to write queries to search entities. It is different from SQL queries. JPQL queries already understand the mappings defined between entities. We can add other conditions if needed. Standard API : It defines a Java-based API to perform searches on the database.
Hibernate is the implementation of JPA. It is the most popular ORM framework, while JPA is the API that defines the standard. Hibernate understands the mappings we add between objects and tables. It ensures that data is retrieved from the database based on the mappings/to store data. It also provides other features on top of JPA.
In this example, we will use spring-boot-starter-data- jpa依赖关系来创建与H2数据库的连接。
Steps1: 打开spring Initializr https://start.spring.io/。
Steps2: 提供 组名称。我们提供了 com.w3codebox 。
Steps3: 提供 工件 ID。我们提供了 spring-boot-jpa-example。
Steps4: 添加依赖项: Spring Web,Spring Data JPA,and H2Database.
Steps5: Click the 生成按钮。当我们单击"生成"按钮时,它会将项目包装在 Jar 文件中,并将其下载到本地系统。
Steps6: 提取 Jar文件并将其粘贴到STS工作区中。
Steps7: 将项目文件夹导入STS。
文件->导入->现有Maven项目->浏览->选择文件夹spring-boot-jpa-example->Complete
导入需要一些时间。
Steps8: 创建一个名为 com.w3codebox.controller 的程序包在步骤 src/main/java 中。
Steps9: 在控制台中创建一个名称为 ControllerDemo 的Controller类。软件包 com.w3codebox.controller 。
ControllerDemo.java
package com.w3codebox.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ControllerDemo { @RequestMapping("/") public String home() { return "home.jsp"; } }
Steps10: 在文件夹 src/main/java中创建另一个名为 com.w3codebox.model 的软件包。
User. Java
package com.w3codebox.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 H2Database.
Steps12: Open application.properties File and configure the following content: Port, Enable H2Console, Data Source,and URL.
application.properties
server.port=8085 spring.h2.console.enabled=true spring.datasource.platform=h2 spring.datasource.url=jdbc:h2:mem:w3codebox
Steps13: : In the folder src/main/Create a file in resources SQL File.
Right-click on the folder src/main/resources->New->File->Provide Filename->Complete
We provided the filename data.sql and insert the following data into it.
data.sql
insert into userdata values(101Tom'); insert into userdata values(102Andrew'); insert into userdata values(103Tony'); insert into userdata values(104Bob'); insert into userdata values(105Sam');
Steps14: : In src Create a folder named webapp folder.
Steps15: using the folder we ControllerDemo Create a JSP file with the name returned by the controller. In ControllerDemo.java, we 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>
Steps16: Run SpringBootJpaExampleApplication.java file. We can see that our application is running on port 8085 to run successfully.
Steps17: Open the browser and call the URL http: //localhost: 8085/h2-console/. It shows the driver class, which we have application.properties the JDBC URL and default username sa configured in the file.
We can also click Test Connection button to test the connection. If the connection is successful, the message "Test Success" is displayed.
Steps18: Click the Connect (Connected) button. It shows that we have User.java defined in the userdata table structure as defined.
Steps19: Execute the following query to view the tables we have inserted data.sql data in the file.
SELECT * FROM USERDATA;