SpringBoot advanced usage

Posted by atulkul on Sat, 15 Jan 2022 06:02:08 +0100

1, SpringBoot advanced usage

1. Lombok plugin

1.1) Maven coordinate query

website: https://mvnrepository.com/
You can now find information about the maven package

1.2) add jar package file

<!--add to lombok rely on-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

1.3) Lombok use

Function: automatically generate get/set/toString/equals/hashCode and other methods of entity objects through the program
Chain loading principle: restart the set method of POJO and return the current object

public User setId(Integer id) {
        this.id = id;
        return this;
    }

Common notes:

@Data   //get/set
@Accessors(chain = true) //Chain loading structure rewriting set method
@NoArgsConstructor  //Nonparametric structure
@AllArgsConstructor //All parameter construction must add no parameter construction provisions!!! Turtle's ass
public class User {
    private Integer id;
    private String name;
    //eclipse key position Ctrl + O windows key position: ctrl+f12/alt+7

1.4) interview questions about Lombok (elementary)

problem: lombok The use of needs in IDE Install plug-ins in advance!!!,If the project is in Linux To deploy and publish in the system, do you need to install plug-ins in advance!!!

answer: No!!!
	reason: lombok Plug in compile time is valid(Compilation period:from xxx.java File compiled as xxxx.class file),Before packing class The file already contains set/get So the project can be run directly after packaging without installing plug-ins!!!.

2. Spring boot integrates Mybatis

2.1) import database

2.1.1) check whether the database is available

Note: normally, the mysql service item starts automatically. Sometimes the database service fails to start for some reason
Problem Description: the database link reports an error and the display link is unavailable
Check service items:

Database version: use mariadb instead of Mysql 5.8

2.1.2) database client tool - SqlYog
Connect to database

SqlYog usage

2.1.3) database import and export

Export database: export the database in mysql as XXX Dump SQL files
Import database: read XXX After the sql file, the tool executes the sql in it, and finally realizes the data import function
Note: the above operations are called database cold backup Generally, in the production environment, in order to ensure the security of data Generally, it will be cold backed up regularly (the period is about 3-7 days) generally in triplicate Cold backup of database is the last effective means to restore data
Features: cold backup is easy to lose data Hot backup can realize real-time backup

2, Spring boot integrates Mybatis

1. Create project

1.1) new maven project

Select maven to create a new project

Edit maven coordinates

pox file imports the jar package file of springBoot
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--coordinate-->
    <groupId>com.jt</groupId>
    <artifactId>springboot_demo2_mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--
      location: SpringBoot Main role integration SSM,Make the use of the framework more simplified
      principle: "Out of the box"
      parent Main role:
             1.SpringBoot It is internally compatible with almost all current third-party frameworks
             2.SpringBoot All compatible versions have been defined on the official website
              (Almost solved the version conflict problem)The version number is hardly written in the future
      generalization: parent Manage other project version information in the tab.
  -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <!--Skip test class packaging-->
        <skipTests>true</skipTests>
    </properties>

    <!--principle: Import on demand  -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <!--springboot Startup item(implement)Inside the package SpringBoot
            The of the project has been completed"integration"(to configure) The user takes it and uses it
            web Import SpringMVC
            -->
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <!--Support hot deployment -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <!--add to lombok rely on-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!--Introducing database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--springBoot Database connection  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!--spring integration mybatis  temporary
           mapper Interface/mapper.xml Mapping file
          -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

    </dependencies>

    <!--SpringBoot Project and Maven A plug-in for integration
        You can perform project packaging through plug-ins/test/Document generation and other operations
        matters needing attention: The plug-in cannot be omitted
        When the project is published: java -jar xxxx.jar  report errors:No master list information!!!!
    -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.5.2</version>
            </plugin>
        </plugins>
    </build>
   

</project>

1.2) edit main startup class

package com.jt;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.jt.mapper") //Create proxy objects for interfaces inside the Spring container
                             //Dynamic proxy object of JDK
public class SpringBootRun {

    //standard notation 
    public static void main(String[] args) {
        SpringApplication.run(SpringBootRun.class, args);
    }
}

1.3) edit POJO entity object

Note: general entity objects only need to add get/set/toString and other methods, without adding construction methods

package com.jt.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * Object relationship mapping configuration:
 *      1.User The object needs to be with the demo_user table binding
 *      2.User The attributes in the object are bound to the fields in the table one by one
 */
@Data
@Accessors(chain = true)
@TableName("demo_user")
//The function of entity object is to pass parameters
//@Component / / there is no need to hand over the entity object to the Spring container for management
public class User implements Serializable {
    //Primary key auto increment
    @TableId(type= IdType.AUTO)
    //Serialization: ensure data transmission integrity
    private Integer id;

    //@TableField( "name")
    //If the attribute has the same name as the field (including hump rule), the annotation can be omitted
    private String name;
    private Integer age;
    private String sex;
}

1.4) function of serial number

Generally, if you need to transfer objects, POJO objects must implement the serialization interface, otherwise the data transmission will inevitably report an error

2. Integrate Mybatis

2.1) steps of integrating Mybatis with SpringBoot

  1. Add jar package file dependency
  2. Spring boot integrates Mybatis
    1). Add profile
    2). Connect to database
  3. Create Mapper interface
  4. Create an XML Mapping file

2.2) import jar package file into pom file

Three packages: mybatis package, database driver package and JDBC package

<!--Introducing database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--springBoot Database connection  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!--spring integration mybatis  temporary  -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

2.3) about data source configuration

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/jt?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: root
serverTimezone=GMT%2B8& %2B= + GMT+8&
useUnicode=true&characterEncoding=utf8& Whether to use unicode Encoding and setting character set
autoReconnect=true Auto reconnect
allowMultiQueries=true Allow batch operation

2.4) Mybatis configuration file application yml

Topics: Java Database MySQL Maven Mybatis