Official website: Click to enter

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>undefined</version>
</dependency>
Copy the code

1: test environment

1.1: Database creation

Create db_mybatis_plus database. Create table user as follows

Insert the following data:

1.2: Springboot project creation

Depend on the introduction of

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </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>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
    </dependencies>
Copy the code

Yml configuration file

spring:
  datasource:
    username: root
    password: yfy57609
    url: JDBC: mysql: / / 1.15.57.103:3306 / db_mybatis_plus? serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver


#mybatis_plus Log configuration
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Copy the code

Logback configuration file


      
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
        </encoder>
    </appender>

    <logger name="com.base22" level="TRACE"/>

    <root level="info">
        <appender-ref ref="STDOUT"/>
    </root>

</configuration>
Copy the code

mapper

Remember to annotate @mapperscan on the startup class

@Repository
public interface UserMapper extends BaseMapper<user> {}Copy the code

Entity class

@Data
public class user {
    private int id;
    private String name;
    private Integer age;
    private String email;
}
Copy the code

2: Add, delete, change and check ybatis_plus

21: Simple insertion

 @Test
    public void insert(a){
        user u=new user();
        u.setName("aaa");
        u.setAge(21);
        u.setEmail("[email protected]");
        int result=userMapper.insert(u);
        System.out.println("Number of rows affected:"+result);
        System.out.println("user id:"+u.getId()); } output: number of rows affected:1
    user id:1412739741353529345
Copy the code

Note: The database ID primary key is not set to increment, and the user ID should default to 0 when inserted. But why is the primary key 1412739741353529345 given after insertion?

Separate database and table strategy

Service branch: A database is divided into several databases according to their service functions

Branch cost: Join cannot be used, and transactions involving multiple databases cannot be used

Master/slave replication: The host performs write operations and the slave performs read operations

Separate database tables: Different business data are stored in different database servers. Vertical split (field column) or horizontal split (data row)

Horizontal split – Primary key autoincrement policy: Each table stores a certain range of data. For example, table 1 stores ids from 1 to 999999, and Table 2 stores ids from 100000 to 199999. The disadvantage is that each table may vary in size, with a table having 1000 entries (most of the id range is deleted) and a table having 90,000 entries.

Horizontal split -hash policy: for example, if there are 10 tables, the value of ID %10 is used to determine which table to put in. For example, the value of ID =15 is put in table 5. The difficulty lies in the selection of the number of databases. The advantage is that the data is evenly distributed. The disadvantage is that it is difficult to extend new tables

Snowflake algorithm: Distributed ID generator:Ensure non-repeatability of primary keys from different tables and order of primary keys from the same table

Mybatis_plus primary key policy

Snowflake algorithm is used by default. The primary key increment is not required for the database

There is also the primary key increment policy: the database is set to primary key increment. The code increment travel is also modified as follows

@Data
public class user {
   @TableId(type = IdType.AUTO)
   private Long id;
   private String name;
   private Integer age;
   private String email;
}
Copy the code

Global setting primary key generation policy (in configuration file) :

mybatis-plus:
 global-config:
   db-config:
     id-type: auto
Copy the code

2.2: Update operation

Modify data by ID

@Test
    public void update(a){
       user u=new user();
       u.setId(0l);
       u.setAge(30);
       int result=userMapper.updateById(u);
        System.out.println("Number of rows affected:"+result);
        System.out.println(u.toString());
    }

Copy the code

Develop norms, habits. Set the creation and update time of data

Mysql > alter database table

The entity class is also modified to add fields:

@Data
public class user {
    private Long id;
    private String name;
    private Integer age;
    private String email;

    private Date createTime;// Automatic hump conversion
    private Date updateTime;
}
Copy the code

The business layer can add the creation time and change the update time through mybatis_Plus automatic fill function instead of manually setting each time

Autofill function

This feature can be used to implement things such as adding create times and changing update times

First add auto-fill annotations on the entity class to the field to be actively populated:

@Data
public class user {
    private Long id;
    private String name;
    private Integer age;
    private String email;

    @TableField(fill = FieldFill.INSERT)
    private Date createTime;// Automatic hump conversion

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}
Copy the code

Then implement the meta-object handling interface:

Generally placed under the handler package

@slf4j (topic = "mybatis_plus autofill ")
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime".new Date(),metaObject);
        this.setFieldValByName("updateTime".new Date(),metaObject);
        log.info("Insert a data, automatically fill in creation time and update time");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime".new Date(),metaObject);
        log.info("Update data, automatically fill in the update time"); }}Copy the code

You can now automatically set certain field values for the object (user in this case). The metaObject passed in here is actually the object passed in when we call the insert or update method, such as usermapper.insert (user). After the insert is called, the insert time and update time are automatically filled for the user, without requiring us to manually call the setter method. The meteObject above contains this user. The setFieldValByName method sets the value for the corresponding field of the object in meteObject. Basically what we’re doing is we’re automatically calling setter methods to set a value

2.3: Optimistic lock

The first step is to inject the plug-in, using the SpringBoot configuration

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(a) {
   MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
   interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
   return interceptor;
}
Copy the code

Annotate @Version on the fields of the entity class

@Version
private Integer version;
Copy the code

2.4: Basic query

2.4.1: Batch Query

  @Test
    public void Beach(a){
       List<user> userList= userMapper.selectBatchIds(Arrays.asList(1.2.3));
        log.info(String.valueOf(userList));
    }
Copy the code

2.4.2: Conditional Query

@Test
    public void select(a){
        Map<String,Object> map=new HashMap<>();
        map.put("name"."yfy");
        map.put("age".30);
        List<user> users=  userMapper.selectByMap(map);
        log.info(String.valueOf(users));
    }
Copy the code

2.4.3: Paging query

Configure the paging plug-in first

 @Bean
    public PaginationInterceptor mybatisPlusInterceptor(a) {
        return new PaginationInterceptor();
    }
    
Copy the code

test

 @Test
    public void selectPage(a){
        Page<user> page=new Page<>(1.5);
        Page<user> pageParam = userMapper.selectPage(page, null);
        List<user> users=pageParam.getRecords();
        log.info(String.valueOf(users));
        System.out.println("Total pages"+pageParam.getPages());
        System.out.println("Total records"+pageParam.getTotal());
        System.out.println("Current page"+pageParam.getCurrent());
        System.out.println("Records per page"+pageParam.getSize());
        System.out.println("Is there a next page?"+pageParam.hasNext());
        System.out.println("Is there a previous page?"+pageParam.hasPrevious());
    }
Copy the code

supplement

2.5: delete

Physically deleted

  @Test
    public void delete(a){
        // Delete by id
        userMapper.deleteById(0);
        // Batch delete
        userMapper.selectBatchIds(Arrays.asList(1.2.3));
        // Customize the delete condition
        Map<String,Object> map=new HashMap<>();
        map.put("name"."yfy");
        userMapper.deleteByMap(map);
    }
Copy the code

Logic to delete

Add logical delete flags

   @Test
   public void logdelete(a){
       userMapper.deleteById(1);
   }
Copy the code

This deletion is an Update operation

3: Conditional constructor

Conditional constructor