SpringBoot integrates Jpa to realize addition, deletion, modification and query functions (Gitee source code is provided)

Foreword: In daily development, it is very time-consuming to always write some simple SQL. Jpa can perfectly help us improve the efficiency of development. We don’t need to write regular SQL by ourselves. Compared with MyBatis, it has simpler and easier-to-use functions. , but MyBatis has a higher degree of freedom than Jpa, so Jpa is more suitable for some small and medium-sized project development, improving the development efficiency of developers. Below I will fully introduce how SpringBoot integrates Jpa to achieve complete additions, deletions and modifications check function. 

Table of contents

1. Import pom dependencies

Two, yml configuration file

Three, table structure SQL

Four, User entity class

Five, Dao persistence layer

6. Example of use

6.1. Query the user named Zhang San

6.2. Page query data

6.3, custom SQL query

6.4. Add a new user data

6.5. Modify a piece of user data

6.6. Delete a piece of user data

7. Gitee source code 

8. Summary


1. Import pom dependencies

Full code:

<dependencies>

        <!-- JPA -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- MySQL驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>

        <!-- lombok依赖包 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
    </dependencies>

Two, yml configuration file

Full code:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: 用户名
    password: 密码
  # JPA配置
  jpa:
    # 在建表的时候,将默认的存储引擎切换为InnoDB
    database-platform: org.hibernate.dialect.MySQLDialect
    # 数据源
    database: mysql
    # 控制台显示sql
    show-sql: true
    hibernate:
      # 更新或创建表结构
      ddl-auto: update

Three, table structure SQL

Full code:

-- jpa.`user` definition

CREATE TABLE `user` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `address` varchar(100) DEFAULT NULL,
  `age` bigint NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Four, User entity class

Commonly used entity class annotations are as follows:

1. @Entity: Used to mark a class as a JPA entity class, indicating that this class will be mapped to a table in the database. In JPA, an entity class must be marked with the @Entity annotation so that JPA can recognize and manage it.

2. @Table: used to specify the name and constraints of the database table corresponding to the entity class.

name: Specifies the name of the table.

schema: Specifies the database schema where the table resides.

catalog: Specifies the database catalog where the table is located.

uniqueConstraints: the unique constraints of the specified table.

3. @Column: Used to specify the mapping relationship between entity class attributes and database table fields.

name: specifies the name of the field.

nullable: Specifies whether the field is nullable.

unique: Specifies whether the field is unique.

length: Specifies the length of the field.

precision: Specifies the precision of the field.

scale: Specifies the number of decimal places for the field.

4. @Id: Used to specify the entity class attribute as the primary key.

5. @GeneratedValue: used to specify the generation strategy of the primary key.

strategy: Specifies the primary key generation strategy, such as AUTO, IDENTITY, SEQUENCE, etc.

6. @Transient: Used to specify that entity class attributes do not need to be persisted to the database.

7. @Access: Used to specify the access method of the attribute, such as FIELD, PROPERTY, etc.

8. @Temporal: used to specify the date/time type mapping between entity class attributes and database table fields.

value: Specifies the date/time type, such as DATE, TIME, TIMESTAMP, etc.

9. @Enumerated: used to specify the enumeration type mapping between entity class attributes and database table fields.

value: Specifies the enumeration type mapping method, such as ORDINAL, STRING, etc.

10. @Embedded: Used to specify the attribute of the entity class as an embedded object.

11. @Embeddable: Used to specify embedded objects.

12. @OneToOne: Used to specify a one-to-one relationship between entity classes.

13. @JoinColumn: Used to specify the names and constraints of foreign key columns.

14. @OneToMany: Used to specify a one-to-many relationship between entity classes.

15. @JoinColumn: Used to specify the names and constraints of foreign key columns.

16. @OrderBy: Used to specify the sorting method of collection properties.

17. @ManyToOne: Used to specify the many-to-one relationship between entity classes.

18. @JoinColumn: Used to specify the names and constraints of foreign key columns.

19. @ManyToMany: Used to specify the many-to-many relationship between entity classes.

20. @JoinTable: Used to specify the name and constraints of the intermediate table.

21. @JoinColumn: Used to specify the names and constraints of foreign key columns.

Full code:

package com.example.jpa.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "user")
public class User {

    @Id
    @Column(name = "id",nullable = false)
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username",nullable = false,length = 100)
    private String username;

    @Column(name = "password",nullable = false,length = 100)
    private String password;

    @Column(name = "sex",nullable = false,length = 1)
    private String sex;

    @Column(name = "address",length = 100)
    private String address;

    @Column(name = "age",nullable = false)
    private int age;
}

Five, Dao persistence layer

Full code:

package com.example.jpa.dao;

import com.example.jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface UserRepository extends JpaRepository<User,Long> {

    /**
     * 根据用户名去查询用户信息
     * @return
     */
    public User findUserByUsername(@Param("username") String username);
    
    /**
     * 自定义SQL查询
     * @return
     */
    @Query(value="select * from user where address like %:address%",nativeQuery=true)
    List<User> findUserByAddressSQL(@Param("address") String address);


}

6. Example of use

The following list some basic additions, deletions, modification and query functions.

6.1. Query the user named Zhang San

Full code:

package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        User user = userRepository.findUserByUsername("张三");
        System.out.println(user);
    }

}

6.2. Page query data

Full code:

package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        Pageable pageable = PageRequest.of(1, 10);
        Page<User> userPage = userRepository.findAll(pageable);
        List<User> userList = userPage.getContent();
    }

}

6.3, custom SQL query

Full code:

package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        List<User> userList = userRepository.findUserByAddressSQL("江苏");
    }

}

6.4. Add a new user data

Full code:

package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.*;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        User user = new User();
        user.setUsername("李四");
        user.setPassword(UUID.randomUUID().toString());
        user.setAddress("江苏南通");
        user.setAge(18);
        user.setSex("男");
        userRepository.save(user);
    }

}

6.5. Modify a piece of user data

Full code:

package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import com.example.jpa.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.UUID;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        User findUserByUsername = userRepository.findUserByUsername("张三");
        findUserByUsername.setPassword(UUID.randomUUID().toString());
        userRepository.save(findUserByUsername);
    }

}

6.6. Delete a piece of user data

Full code:

package com.example.jpa;

import com.example.jpa.dao.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;

@SpringBootTest
class JpaApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    void contextLoads() {
        userRepository.deleteById(18L);
    }

}

7. Gitee source code 

Code cloud address: SpringBoot integrates Jpa to realize the function of adding, deleting, modifying and checking

8. Summary

The above is my sharing of the basic functions of adding, deleting, modifying and checking SpringBoot’s integration of Jpa. If you have any questions, welcome to discuss in the comment area!

Guess you like

Origin blog.csdn.net/HJW_233/article/details/132575085