1. SpringBoot source code analysis

1.1 “Out of the box” instructions

Note: If the user needs to use certain frameworks/features, only a small amount of configuration is required to achieve this feature. Note 2: The SpringBoot program starts executing multiple boot items in sequence. When a specific JAR package file is added to the POM.xml file, the boot item loads the file and instantiates the object. Complete automatic assembly. Thus realized out of the box effect.

The Official website of SpringBoot provides mainstream assembly configuration items, which can be implemented without too much configuration. However, if the Configuration items are not provided on the official website, you need to manually use the Configuration class to customize the Configuration items.

Summary: the official website is configured directly guide package, the official website is not configured manually

1.2 Types of automatic selectors

Display method: Add the following codes to the configuration file to display the debug process items

============================
CONDITIONS EVALUATION REPORT
============================


Positive matches:
-----------------

   AopAutoConfiguration matched:
      - @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)

   AopAutoConfiguration.ClassProxyingConfiguration matched:
      - @ConditionalOnMissingClass did not find unwanted class 'org.aspectj.weaver.Advice'(OnClassCondition) - the @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition)

   DispatcherServletAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'(OnClassCondition)
      - found 'session' scope (OnWebApplicationCondition)

   DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched: - the @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'(OnClassCondition)
      - Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)

   DispatcherServletAutoConfiguration.DispatcherServletRegistrationConfiguration matched: - the @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'(OnClassCondition)
      - DispatcherServlet Registration did not find servlet registration bean (DispatcherServletAutoConfiguration.DispatcherServletRegistrationCondition)...Copy the code

2. Use of advanced SpringBoot properties

2.1 About the SpringBoot Configuration File

  • Basic configuration: key-value structure

2.1.1 the properties file

Features:

  • 1. The nature of the data edited by Properties isType StringThe string
  • 2. Use the key value structure in properties= no.Method dynamic linking
  • 3. Properties do not need to be added"
  • 4. The default character set encoding for loading in properties isISO-8859-1If you write Chinese, you need to specify the character set

Modify character set configuration:

2.1.2 yml file

2.2 Assigning an attribute

2.2.1 Service Requirements

When using the SpringBoot program to integrate the third-party framework, if the attribute information is written in the code, the scalability of the program is not good: can dynamic access to attribute information?

2.2.2 Using the @value attribute to assign a Value

1). Edit the YML configuration file

# features:
# 1. In YML, key/value is linked with :+ space
# 2. Indent files in YML with hierarchy.
# 3. The default character set for YML programs to load is UTF-8 encoding. So there will be no Chinese garbled problem.
server:
  port: 8080

# Test Case 1: Attribute Assignment Precautions It is best to add a business name when editing a key
redis:
  host: 10.0. 04.
  port: 6379
Copy the code

2). Use the @value attribute to assign a Value

RedisController

@RestController
public class RedisController {

    // Requirement: get attribute value expressions dynamically from the Spring container: SpringEL expressions for short spEL expressions
    @Value("${redis.host}")
    private String host;  / / = "10.0.0.4"
    @Value("${redis.port}")
    private Integer port; //  = 6380

    @RequestMapping("/getNode")
    public String getNode(a){

        return "Redis node."+host+":"+port; }}Copy the code

2.2.3 Assign values to properties using properties

1). Edit the properties configuration file

redis.properties

Note: The key must be unique
Redispro. host= IP address of 192.168.1.1
redisPro.port=7000
Copy the code

2). The editor Controller

RedisProController

@RestController
// Load the configuration file dynamically
@PropertySource(value = "classpath:/properties/redis.properties",encoding = "UTF-8")
public class RedisProController {

    @Value("${redisPro.host}")
    private String host;
    @Value("${redisPro.port}")
    private Integer port;

    @RequestMapping("/getNodePro")
    public String getNode(a){

        return "Redis node."+host+":"+port; }}Copy the code

2.3 Environment switching test

2.3.1 Service Description

You may encounter changes in office location during development. Development may be done in the company, but online deployment needs to be done in party A. The development and test environments may differ. If frequent changes are inefficient.

2.3.2 Switching the environment

# Choose the default environment SpringCloud configuration center mechanism to manage YML configuration files uniformly
spring:
  profiles:
    active: test
---
# features:
# 1. In YML, key/value is linked with :+ space
# 2. Indent files in YML with hierarchy.
# 3. The default character set for YML programs to load is UTF-8 encoding. So there will be no Chinese garbled problem.
server:
  port: 8080

Define the environment name
spring:
  config:
    activate:
      on-profile: prod


# Test Case 1: Attribute Assignment Precautions It is best to add a business name when editing a key
redis:
  host: 10.0. 04.
  port: 6379

The original YML is split into 2 YML
---
server:
  port: 9000

Define the environment name
spring:
  config:
    activate:
      on-profile: test
redis:
  host: 192.1681.1.
  port: 7000

Copy the code

2.4 Hot Deployment Test

2.4.1 Adding a JAR Package

<! > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId>  </dependency>Copy the code

2.4.2 IDEA configuration

Key combination: CTRL + Shift + Alt + / or CTRL + Alt + A

Select the hot deployment tool

2.5 introduction of lombok

2.5.1 Importing jar Packages

        <dependency>
            <groupId>repository.org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.1816.</version>
        </dependency>
Copy the code

2.5.2 Verifying whether plug-ins are installed

2.5.3 Use of Annotations

@Data    // Dynamically add methods like get/set/toString/equals
@AllArgsConstructor // Add constructor
@NoArgsConstructor// Add a no-parameter construct
@Accessors(chain = true)// introduce chain loading, override set method
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
}
Copy the code

Introduce chain loading method, rewrite set method

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String Hello(a){
        User user = new User();
        user.setName("The wind").setAge(18).setSex("Male");
        
        return "Hello SpringBoot";
    }
Copy the code

2.5.4 Lombok interview Questions

Note: Lombok plug-in needs to be added to IDEA during the development stage, so that the program can run normally. Question: Does the Lombok plug-in need to be installed in Linux if the project needs to run on Linux?

XXX. Java is compiled via the IDE to add get/set methods dynamically to XXX. Class files, so the project is typed into XX.jar /xxx.war with get/set methods already included. So you don’t need to add

2.6 SpringBoot integration with Mybatis

2.6.1 Creating a Project

1). Select the project name

Select the jar package 2). Edit the pom.xml file


      
<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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>
    <groupId>com.jt</groupId>
    <artifactId>springboot_demo2</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>springboot_demo2</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Copy the code

2.6.2 Editing the Data Source Configuration

application.yml

SpringBoot data source configuration
spring:
  datasource:
    url: JDBC: mysql: / / 127.0.0.1:3306 / JTDB? serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: root
Copy the code
  • ServerTimezone =GMT%2B(+)8 Indicates zone 08 GMT
  • &useunicode =true&characterEncoding=utf8 whether to useUnicode encoding to use the utf-8 character set
  • &autoreconnect =true Whether to reconnect after the connection is disconnected.
  • &allowMultiQueries=true Whether batch operations are allowed
   <insert id="xxxx">
		<! SQL > select * from 'select * from' where 'allowMultiQueries' =true
		insert into xxx1 values (xxx,xx,xx);
		insert into xxx2 values (xxx,xx,xx);
		insert into xxx3 values (xxx,xx,xx);
	</insert>
Copy the code

2.6.3 Editing Mybatis Configuration

application.yml

Mybatis # SpringBoot integration
mybatis:
  The alias package is used to automatically concatenate POJO objects later
  type-aliases-package: com.jt.pojo
  Import the Mapper configuration file
  mapper-locations: classpath:/mybatis/mappers/*.xml
  # Enable hump mapping
  configuration:
    map-underscore-to-camel-case: true
Copy the code

Complete configuration:

application.yml

Configure the port number
server:
  port: 8090
  servlet:
    context-path: /
    
SpringBoot data source configuration
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: JDBC: mysql: / / 127.0.0.1:3306 / JTDB? serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: root

Mybatis # SpringBoot integration
mybatis:
  The alias package is used to automatically concatenate POJO objects later
  type-aliases-package: com.jt.pojo
  Import the Mapper configuration file
  mapper-locations: classpath:/mybatis/mappers/*.xml
  # Enable hump mapping
  configuration:
    map-underscore-to-camel-case: true
Copy the code

2.6.4 Editing a Mapper Interface

  1. Copy the previous POJO class

User

@Data    // Dynamically add methods like get/set/toString/equals
@AllArgsConstructor // Add constructor
@NoArgsConstructor// Add a no-parameter construct
@Accessors(chain = true)// introduce chain loading to override set
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
}
Copy the code
  1. Create UserMapper class

UserMapper

@Mapper
public interface UserMapper {
    // Query the data annotation mode of all users/XML mapping file mode
    List<User> findAll(a);
}
Copy the code

Edit the mapping file:


      
<! DOCTYPEmapper
  PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <! -- Namespace needs to be consistent with the interface path -->
<mapper namespace="com.jt.mapper.UserMapper">
		<! -- id=" attributes need to be consistent with interface methods "resultType=" Package name. Mybatis encapsulates the resultSET as an object -->
	<select id="findAll" resultType="User">
		select * from user
	</select>

	<! Service requirements: Fields in the table: user_id,user_age, attributes in the user_sex object: userId,userAge,userSex Field user_id ~ ~ ~ ~ mapping, automatically capitalize the first letter after place _ line ~ ~ ~ ~ ~ userId dynamic attributes assigned to ~ ~ ~!!!!!! If you enable hump rule mapping field: user_id,user_age attribute: user_id,user_age Note: If hump rule mapping is enabled, it must be implemented as required.

</mapper>
Copy the code

2.6.5 Editing the main boot class

@SpringBootApplication
// Import the mybatis interface package path
@MapperScan("com.jt.mapper")
public class SpringbootDemo2Application {

    public static void main(String[] args) { SpringApplication.run(SpringbootDemo2Application.class, args); }}Copy the code

2.6.6 Editing test methods

@SpringBootTest  // When the program executes the @test method, it starts the springBoot container instantiation object. And then the program calls
class SpringbootDemo2ApplicationTests {
    // Dynamically inject the cgBlib JDK for instance objects of the Mapper interface
    @Autowired    Dependency injection 1. Injection by type 2. Injection by name
    // @qualifier (" Injected property name ")
    private UserMapper userMapper;


    @Test
    public void testMybatis(a) {
        System.out.println(Enter the type of the proxy object:+userMapper.getClass()+"The JDK agent"); List<User> userList = userMapper.findAll(); System.out.println(userList); }}Copy the code



2.7 MybatisPlus

2.7.1 ORM thought

Object Relational Mapping (ORM, OR O/RM, or O/R Mapping) is a programming technique used to transform data between different types of systems in object-oriented programming languages.

The ORM thought framework: Mybatis | Hibernate (configuration) red

Advantages: programmer simple operation disadvantages: relatively high execution overhead (slow) Summary: operate the database in the way of objects

2.7.2 Implementation principle of MybatisPlus

Analyze the nature of the problem:

  • 1. Object ——- property
  • 2. Table ——– field

1. How to associate objects with tables? Implement with custom annotations 2. How to simplify CRUD methods? Define a public Mapper interface to which you add the CURD method 3. Objects need to be converted into Sql statements to be converted according to a specific syntax

Sql: insert into user Sql: Insert into user Values (Attribute value…) ; After the formal SQL splicing, the SPLiced SQL will be delivered to Mybatis for execution


2.7.3 MybatisPlus (MP) is introduced

Website:mybatis.plus/

MyBatis-Plus (Opens New Window) (MP) is a new enhancement tool for MyBatis (Opens New Window), which is designed to simplify development and improve efficiency.

Features:

  • No intrusion: only enhancements are made, no changes are made, and its introduction will not affect the existing project, as smooth as silk
  • Low loss: Basic CURD will be injected automatically upon startup, with basically no loss in performance and direct object-oriented operation
  • Powerful CRUD operations: built-in universal Mapper, universal Service, only through a small amount of configuration can achieve a single table most CRUD operations, more powerful condition constructor, to meet all types of use requirements
  • Support Lambda form call: through Lambda expressions, it is convenient to write all kinds of query conditions, without worrying about field write errors
  • Support automatic generation of primary keys: support up to four primary key policies (including distributed unique ID generator – Sequence), can be freely configured, perfect solution to the primary key problem
  • Support for ActiveRecord mode: Support for ActiveRecord form calls, entity classes only need to inherit from Model classes to perform powerful CRUD operations
  • Support custom global universal operations: support Write once (use anywhere)
  • Built-in code generator: using code or Maven plug-in can quickly generate Mapper, Model, Service, Controller layer code, support template engine, more than a lot of custom configuration you to use
  • Built-in paging plug-in: Based on MyBatis physical paging, developers do not need to care about specific operations, after configuring the plug-in, write paging is equal to ordinary List query
  • The paging plug-in supports a variety of databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer, etc
  • Built-in performance analysis plug-in: outputs Sql statements and their execution time. It is recommended to enable this function during development and testing to quickly find out slow queries
  • Built-in global interception plug-in: provides intelligent analysis and blocking of delete and UPDATE operations on all tables, and can customize interception rules to prevent misoperations

2.8 MybatisPlus(MP) Introduction case

2.8.1 Importing jar Packages

		<! Mybatisjar = Mybatisjar = Mybatisjar
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.2</version>
		</dependency>
Copy the code

2.8.2 Editing the YML Configuration File

server:
  port: 8090
  servlet:
    context-path: /
    
SpringBoot data source configuration
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: JDBC: mysql: / / 127.0.0.1:3306 / JTDB? serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: root

# mybatis - plush configuration
mybatis-plus:
  The alias package is used to automatically concatenate POJO objects later
  type-aliases-package: com.jt.pojo
  Import the Mapper configuration file
  mapper-locations: classpath:/mybatis/mappers/*.xml
  # Enable hump mapping
  configuration:
    map-underscore-to-camel-case: true
Copy the code

2.8.3 Editing POJO Mapping

@Data    // Dynamically add methods like get/set/toString/equals
@AllArgsConstructor // Add constructor
@NoArgsConstructor// Add a no-parameter construct
@Accessors(chain = true)// introduce chain loading to override set
@TableName("user")  // Import the table name
public class User {  // Rule: If the identity field name is consistent with the attribute (including the hump rule), it can be omitted
    
    @TableId(type = IdType.AUTO)  // Identifies the primary key, which is incremented
    private Integer id;
    //@TableField(value = "name")
    private String name;
    private Integer age;
    private String sex;
}

Copy the code

2.8.4 Inheriting public interface methods

// @mapper () // Create a proxy object for the interface and give it to Spring to manage
// Precautions!!!!! Generic < XXX > must be added when inheriting a parent interface
public interface UserMapper extends BaseMapper<User> {
    // Query the data annotation mode of all users/XML mapping file mode
    List<User> findAll(a);
}
Copy the code

2.8.5 MP test

	@Test
	public void testMP(a){
		SQL > select * from user; // Select * from user
		List<User> userList = userMapper.selectList(null);
		System.out.println(userList);
	}

Copy the code


2.8.6 PRINCIPLE of MP Dynamic Sql

Object: the associated data table | associated table fields. Database execution: Sql statement. Java foundation: reflection mechanism

SQL: Java code: usermapper.insert (user) Insert into user(name,age,sex) values (name,age,sex) String value = user.getName()