SpringBoot integrates Spring Data JPA to access MySQL

Keywords: Java MySQL Spring Spring Boot


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




    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
    database: MySQL
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true
      ddl-auto: update


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)
public class User {
	//@Id and @GeneratedValue are used to identify the primary key in the corresponding database table for User
    @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() {

Here we also stick out the introduced packages to prevent people from misleading them


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

public class UserServiceImplTest {
    UserDao userDao;

    //Query All
    public void queryAll(){

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

  1. Single Add
    public void add() {
        User user = new User(null, "test", "male", "aaa", "a@qq.com");

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

    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");

Delete operation

  1. Delete individually based on id
    public void delete() {
        User user = new User();
  1. Bulk Delete Based on id
    public void delete() {
        List<Integer> list = new ArrayList<>();

Modify Action

    public void update() {
        //Get user object with id 8
        User user = userDao.findUserById(8);
        //Submit modifications
        User user1 =userDao.save(user);
        //Print modified results

Query operation

    public void query() {
        //Query All
        //Query by id
        //Conditional query for all users of male gender
        User user = new User();
        Example<User> example = Example.of(user);  // Custom matching rules are not built here, default matching rules are used

        //Query a user with male name test2

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


The above content belongs to personal notes collation. If there are any errors, you are welcome to criticize and correct them!

Posted by turbolemon on Mon, 06 Sep 2021 13:35:45 -0700