springboot integration jpa entry

Posted by NSH on Thu, 03 Mar 2022 16:46:50 +0100

springboot integration jpa entry

The entry case writes a crud of jpa single table

1. Prepare the springboot project

Introduce dependency


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <description>Demo project for Spring Boot</description>

        <!--springfox swagger official Starter-->
        <!--springboot integration jpa Dependence of-->
        <!--mysql Drive connection dependency-->





2.application.properties configure jpa related


# apply name
# Application service WEB access port
#If it is created, it will not be created again
#The console displays sql statements

Several properties of DDL Auto

  • create: * * every time you run the program, the table will be recreated, so the data will be lost
  • Create drop: * * each time the program runs, the table structure will be created first, and then the table will be cleared at the end of the program
  • upadte: * * every time you run the program, a table will be created when there is no table. If the object changes, the table structure will be updated. The original data will not be cleared, but only updated (recommended)
  • validate: * * the running program will verify whether the data is the same as the field type of the database, and an error will be reported if the * * field is different**

Spring is normally used jpa. hibernate. DDL auto = update mode, so manual table creation can be skipped here

3. Build entity class


Normally, spring boot integrates jpa's web project, and the annotations used by entity classes are basically the following contents




4. If parameter verification is required, the annotation of parameter verification can be added

package com.example.demo.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.util.Date;

 * @author shaoming
 * @Date: 2021/4/20 17:41
 * @Description:

 * swagger annotation
@ApiModel(value = "UserInfo Entity class",description = "The corresponding database table name is user")
 * lombok Notes for
@Accessors(chain = true)
 * jpa Notes for
@Table(name = "user")
public class UserInfo {
     * IDENTITY Indicates that the primary key is automatically incremented
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    @ApiModelProperty(value = "Primary key id")
    private Integer id;
    @Column(name = "user_name",nullable = false)
    @ApiModelProperty(value = "User name")
    private String userName;
    @Column(name = "create_time",nullable = false)
    @ApiModelProperty(value = "Creation time")
    private Date createTime;
    @Column(name = "update_time",nullable = false)
    @ApiModelProperty(value = "Modification time")
    private Date updateTime;
    @Column(name = "salary",nullable = false)
    @ApiModelProperty(value = "salary")
    private Double salary;
    @Column(name = "address")
    @ApiModelProperty(value = "address")
    private String address;

Common annotations for jpa entity classes

3.1 @Entity

Identify that the entity class is a JPA entity and tell JPA to generate an entity class correspondence table when the program runs

3.2 @Table

Specify the table name of the generated database. If the table name corresponds to the entity class name, the annotation can be omitted

3.3 @Id

The variable in the identification class is the primary key

3.4 @GeneratedValue

Set the primary key generation policy. This method depends on the specific database

  • TABLE: * * use a specific database TABLE to save the primary key
  • SEQUENCE: * * generate the primary key according to the SEQUENCE of the underlying database, provided that the database supports the SEQUENCE. This value should be used together with the generator, which specifies the generator used to generate the primary key (it may be a SEQUENCE written by orcale itself).
  • IDENTITY: * * the primary key is automatically generated by the database (mainly databases that support automatic growth, such as mysql)
  • AUTO: * * the primary key is controlled by the program and is also the default value of GenerationType.

'IDENTITY' is used for mysql primary key

3.5 @Column

Indicates that the field name corresponding to the attribute is personalized

The name attribute defines the name of the field corresponding to the marked field in the database table;

The unique attribute indicates whether the field is a unique identifier. The default is false. If a field in the Table needs unique identification, you can use either this tag or @ UniqueConstraint in the @ Table tag.

nullable property indicates whether the field can be null. The default value is true.

The insertable attribute indicates whether the value of this field needs to be inserted when inserting data using the "INSERT" script.

The updatable property indicates whether the value of this field needs to be updated when inserting data using the "UPDATE" script. insertable and updatable attributes are generally used for read-only attributes, such as primary keys and foreign keys. The values of these fields are usually generated automatically.

The columnDefinition property indicates the SQL statement created by this field when creating a table. It is generally used when generating a table definition through Entity. (that is, if the table in the DB has been built, this attribute is unnecessary.)

The table attribute defines the name of the table containing the current field.

The length property indicates the length of the field. This property is valid only when the field type is varchar. The default is 255 characters.

precision and scale
The precision attribute and scale attribute represent precision. When the field type is double, precision represents the total length of the value, and scale represents the number of decimal places.

3.6 @Transient

Indicates that the attribute is not a mapping of database table fields, which will be ignored by the ORM framework

4. Build dao layer

public interface UserDao extends JpaRepository<UserInfo,Integer>  {

4. Test

package com.example.demo;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.UserInfo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;
import java.util.Optional;

class DemoApplicationTests {
    private UserDao userDao;

    void contextLoads() {

     * newly added
    public void testSave() {
        UserInfo user = new UserInfo();
        user.setAddress("address").setCreateTime(new Date())
                .setId(null).setUpdateTime(new Date()).setSalary(1000.0)
        UserInfo saveUserInfo = userDao.save(user);
         * save()The return value is used to save the data of this record

     * modify
     * Note that the modification method name is also save(), but the primary key field should be passed in
     * Then modify according to the id
    public void testUpdate() {
        UserInfo user = new UserInfo();
        user.setAddress("addressUpdate111").setCreateTime(new Date())
                .setId(1).setUpdateTime(new Date()).setSalary(1000.0)
         * save()The data used to update the return value is to save the record
        UserInfo updateUserInfo = userDao.save(user);


     * Delete information according to id
     * no return value
    public void testDelete() {

     * Query all
    public void testFindAll() {

     * Query by id
    public void testfindById() {
        Optional<UserInfo> userInfoOptional = userDao.findById(1);
        UserInfo userInfo = userInfoOptional.get();


Topics: Java Database Spring Boot