Preface
JPA was introduced to simplify the development of persistence layers and integrate ORM technology, ending the situation where ORM frameworks such as Hibernate, TopLink, JDO and so on operate independently.JPA is developed on the basis of the existing ORM framework and is easy to use and highly scalable.Overall, JPA includes the following three technologies:
ORM Mapping Metadata: Supports both XML and annotation forms of metadata that describe mapping relationships between objects and tables
API: Operate entity objects to perform CRUD operations
Query Language: Avoid tight coupling of the program's SQL statements by querying data through object-oriented rather than database-oriented query language (JPQL)
Official Spring Data JPA Documentation
Spring Data JPA is part of the Spring Data family and makes it easy to implement a JPA-based repository.This module handles enhanced support for JPA-based data access layers.It makes it easier to build Spring-driven applications that use data access technology.
Implementing a data access layer for an application has been a hassle for quite some time.Too much boilerplate code must be written to perform simple queries and to perform paging and auditing.Spring Data JPA is designed to significantly improve the implementation of the data access layer by reducing the amount of work actually needed.As a developer, you write repository interfaces, including custom finder methods, and Spring automatically provides the implementation.
Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.
Implementing a data access layer of an application has been cumbersome for quite a while. Too much boilerplate code has to be written to execute simple queries as well as perform pagination, and auditing. Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that's actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.
This article provides an initial demonstration of how to use Spring Data JPA to perform basic CURD operations on mysql databases
The complete code for the instance will be placed at the end of the article
Spring Boot Integrates Spring Data Jpa Instances
1. Project structure
2. Database preparation
The table-building statement shows me another article using the same table SpringBoot Integration mybatis-plus - Getting Started Ultra Detail
There are some similarities between mybatis-plus and Spring Data JPA
3,pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency>
4,application.yml
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybits?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8 username: root password: aaaa jpa: database: MySQL database-platform: org.hibernate.dialect.MySQL5InnoDBDialect show-sql: true hibernate: ddl-auto: update
5,User.java
import lombok.*; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; //The @Entity annotation identifies that the User class is a persisted entity //@Data and @NoArgsConstructor are annotations in Lombok.Set, Get functions, and constructors without parameters are automatically generated for each parameter. //If you don't know Lombok yet, take a look at this article: //[Use and principles of the Java development artifact Lombok](https://www.jianshu.com/p/422f151fccd3) @Entity @Data @NoArgsConstructor @AllArgsConstructor public class User { //@Id and @GeneratedValue are used to identify the primary key in the corresponding database table for User @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String sex; private String pwd; private String email; //Print this object public void println() { System.out.println(this); } }
Here we also stick out the introduced packages to prevent people from misleading them
UserDao.java
public interface UserDao extends JpaRepository<User, Integer> { }
As you can see, this interface inherits JpaRepository <Entity, ID>, spring-data-jpa and only needs this information to help you do common things: add, delete, and change.
This section does not specifically expand on all the methods contained in JpaRepository, and addicts simply by using the simplest add-delete checks
Test class UserServiceImplTest.java
To simplify the article, do not write direct test classes for the server layer
import com.king.bean.User; import com.king.dao.UserDao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.*; @SpringBootTest @RunWith(SpringJUnit4ClassRunner.class) public class UserServiceImplTest { @Autowired UserDao userDao; //Query All @Test public void queryAll(){ userDao.findAll().forEach(System.out::println); } }
Run Results
select user0_.id as id1_0_, user0_.email as email2_0_, user0_.name as name3_0_, user0_.pwd as pwd4_0_, user0_.sex as sex5_0_ from user user0_
Introduction to basic CURD operations
Add Operation
- Single Add
@Test public void add() { User user = new User(null, "test", "male", "aaa", "a@qq.com"); userDao.saveAndFlush(user); //userDao.save(user); }
One example is saveAndFlush and there is a save method to refer to this article
Differences between save and saveAndFlush in JPA
2. Bulk Add
@Test public void add2() { List<User> list = new ArrayList<>(); for (int i = 20; i < 40; i++) { User user1 = new User(null, "test" + i, i % 2 == 0 ? "male" : "female", "aaaa", "a" + i + "@qq.com"); list.add(user1); } userDao.saveAll(list); }
Delete operation
- Delete individually based on id
@Test public void delete() { User user = new User(); user.setId(20); userDao.delete(user); }
- Bulk Delete Based on id
@Test public void delete() { List<Integer> list = new ArrayList<>(); list.add(21); list.add(22); userDao.deleteAllById(list); }
Modify Action
@Test public void update() { //Get user object with id 8 User user = userDao.findUserById(8); user.println(); user.setEmail("update@qq.com"); //Submit modifications User user1 =userDao.save(user); //Print modified results user1.println(); }
Query operation
@Test public void query() { //Query All userDao.findAll().forEach(System.out::println); //Query by id userDao.findById(8).get().println(); //Conditional query for all users of male gender User user = new User(); user.setSex("male"); Example<User> example = Example.of(user); // Custom matching rules are not built here, default matching rules are used userDao.findAll(example).forEach(System.out::println); user.setName("test2"); //Query a user with male name test2 userDao.findOne(example).get().println(); }
Summary: The above is the most basic curd operation in Spring Data Jpa, but this is not everything in jpa, and its power is not limited to it.
Finally, attach the source code for my demo
Github
https://github.com/KingJin-web/springboot/tree/master/mybatis_plus
Gitee
https://gitee.com/king__gitee/springboot/tree/master/jpa
The above content belongs to personal notes collation. If there are any errors, you are welcome to criticize and correct them!