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

pom.xml

<?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">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>
    <dependencies>
        <!--springfox swagger official Starter-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!--springboot integration jpa Dependence of-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!--mysql Drive connection dependency-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.example.demo.DemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2.application.properties configure jpa related

application.properties

# apply name
spring.application.name=demo
# Application service WEB access port
server.port=8080
spring.datasource.url=jdbc:mysql://127.0.0.1/jpa?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
#If it is created, it will not be created again
spring.jpa.properties.hibernate.hbm2ddl.auto=update
#The console displays sql statements
spring.jpa.show-sql=true

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

explain:

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

1.lombok

2.jpa

3.swagger

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
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
/**
 * jpa Notes for
 */
@Entity
@Table(name = "user")
public class UserInfo {
    @Id
    /**
     * 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

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

unique
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
nullable property indicates whether the field can be null. The default value is true.

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

updatable
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.

columnDefinition
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.)

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

length
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

@Repository
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;

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    private UserDao userDao;

    @Test
    void contextLoads() {
    }

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

    /**
     * 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
     */
    @Test
    public void testUpdate() {
        UserInfo user = new UserInfo();
        user.setAddress("addressUpdate111").setCreateTime(new Date())
                .setId(1).setUpdateTime(new Date()).setSalary(1000.0)
                .setUserName("updateUserName");
        /**
         * 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
     */
    @Test
    public void testDelete() {
        userDao.deleteById(1);
    }

    /**
     * Query all
     */
    @Test
    public void testFindAll() {
        userDao.findAll().forEach(System.out::println);
    }

    /**
     * Query by id
     */
    @Test
    public void testfindById() {
        Optional<UserInfo> userInfoOptional = userDao.findById(1);
        UserInfo userInfo = userInfoOptional.get();
        System.out.println(userInfo);
    }

}

Topics: Java Database Spring Boot