MybatisPlus use

Mybatisplus

Import dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </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>

    <!--mybatis-plus-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.0.5</version>
    </dependency>

    <!--mysql-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <!--lombok用来简化实体类-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

** Note: ** introducing MyBatis-Plusplease do not re-introduced later MyBatisas well MyBatis-Spring, to avoid problems caused due to differences between versions.

Configuration file changes

In the application.propertiesAdd configuration MySQL database configuration file:

mysql5

#mysql database connection

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus

mysql8 and above (spring boot 2.1)

**Note: **driver and url changes

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8

note:

1. The url here uses the suffix?serverTimezone=GMT%2B8, because Spring Boot 2.1 integrates the 8.0 version of the jdbc driver, this version of the jdbc driver needs to add this suffix, otherwise the following error will be reported when running the test case:

java.sql.SQLException: The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized or represents more

2. The driver-class-name here uses com.mysql.cj.jdbc.Driver. It is recommended to use this driver in jdbc 8. The previous com.mysql.jdbc.Driver has been deprecated, otherwise it will be used when running test cases. There is WARN information

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-K5986CNT-1611036596455) (C:\Users\王东梁\AppData\Roaming\Typora\typora-user-images\ image-20210118190725238.png)]

Instructions for use

1. Import dependencies

2. Write database connection configuration

3. Write a mapper to inherit from BaseMapper and add @Repository to let the spring container recognize

4. The main startup class is scanned @MapperScan("com.atguigu.mpdemo1010.mapper")

Primary key strategy

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-dUyIgHO6-1611036596458) (C:\Users\王东梁\AppData\Roaming\Typora\typora-user-images\ image-20210118191602545.png)]

1. Database self-increasing sequence or field

2. UUID

3. Variant of UUID

ODX}_8Z)C

4. Redis Generate ID

When using a database to generate ID performance is not enough, we can try to use Redis to generate ID. This mainly depends on Redis being single-threaded, so it can also be used to generate a globally unique ID. It can be realized with Redis's atomic operations INCR and INCRBY.

You can use Redis cluster to get higher throughput. Suppose there are 5 Redis in a cluster. You can initialize the value of each Redis to be 1, 2, 3, 4, 5, and then the step size is 5. The IDs generated by each Redis are:

A:1,6,11,16,21

B:2,7,12,17,22

C:3,8,13,18,23

D:4,9,14,19,24

E:5,10,15,20,25

5. Twitter's snowflake algorithm (snowflake algorithm)

Snowflake is Twitter's open source distributed ID generation algorithm, and the result is a long ID. The core idea is: use 41bit as the number of milliseconds, 10bit as the machine ID (5 bits are the data center, 5 bits of the machine ID), and 12bit as the serial number within milliseconds (meaning that each node can generate every millisecond 4096 IDs), and there is a sign bit at the end, which is always 0.

6. Use zookeeper to generate a unique ID

The primary key is a number VS a string

@TableId(type = IdType.ID_WORKER) //mp自带策略,生成19位值,数字类型使用这种策略,比如long
//@TableId(type = IdType.ID_WORKER_STR) //mp自带策略,生成19位值,字符串类型使用这种策略

Time auto fill

first step

Add annotations in entity classes

//create_time
@TableField(fill = FieldFill.INSERT)
private Date createTime;

//update_time
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

Second step

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-KBk013TR-1611036596461) (C:\Users\王东梁\AppData\Roaming\Typora\typora-user-images\ image-20210118200532206.png)]

Create a class, implement the interface MetaObjectHandler, and implement the methods in the interface

package com.atguigu.mpdemo1010.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    

    //使用mp实现添加操作,这个方法执行
    @Override
    public void insertFill(MetaObject metaObject) {
    
    
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);

        this.setFieldValByName("version",1,metaObject);
    }

    //使用mp实现修改操作,这个方法执行
    @Override
    public void updateFill(MetaObject metaObject) {
    
    
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

Fields in the database VS entity classes

In the database: create_time

In the entity class: creanteTime

Optimistic lock

The version is automatically filled with the same time as the time or set the default value in the database

first step

@Version
private Integer version;//版本号

Second step

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-crGLmfQE-1611036596466) (C:\Users\王东梁\AppData\Roaming\Typora\typora-user-images\ image-20210118212859965.png)]

Customize a configuration class to add an optimistic lock plugin in it

//乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
    
    
    return new OptimisticLockerInterceptor();
}

And get mapperscan from the startup class to the configuration class

Note: optimistic lock must be checked first and then changed, otherwise optimistic lock will be invalid

Pagination

first step

Configure paging plugin

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-N0ZReWsf-1611036596469) (C:\Users\王东梁\AppData\Roaming\Typora\typora-user-images\ image-20210118214406225.png)]

/**
 * 分页插件
 */
@Bean
public PaginationInterceptor paginationInterceptor() {
    
    
    return new PaginationInterceptor();
}

Write code

@Test
public void testPage() {
    
    
    //1 创建page对象
    //传入两个参数:当前页 和 每页显示记录数
    Page<User> page = new Page<>(1,3);
    //调用mp分页查询的方法
    //调用mp分页查询过程中,底层封装
    //把分页所有数据封装到page对象里面
    userMapper.selectPage(page,null);

    //通过page对象获取分页数据
    System.out.println(page.getCurrent());//当前页
    System.out.println(page.getRecords());//每页数据list集合
    System.out.println(page.getSize());//每页显示记录数
    System.out.println(page.getTotal()); //总记录数
    System.out.println(page.getPages()); //总页数

    System.out.println(page.hasNext()); //下一页
    System.out.println(page.hasPrevious()); //上一页

}

Tombstone

first step

@TableLogic
private Integer deleted;

Second step

Configure in application.properties (1 is the deleted state, 0 is the non-deleted state) (the default configuration does not need to be modified)

Configure the plug-in in the configuration class as above

//逻辑删除插件
@Bean
public ISqlInjector sqlInjector() {
    
    
    return new LogicSqlInjector();
}

note:

After adding logical deletion, query and other operations will be automatically spliced ​​deleted=0 for splicing

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-3oO2CCa4-1611036596470) (C:\Users\王东梁\AppData\Roaming\Typora\typora-user-images\ image-20210118215717249.png)]

Performance analysis plugin

Find slow SQL

first step

Configuration class for configuration, same as above

/**
 * SQL 执行性能分析插件
 * 开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长
 *
 * 三种环境
 *      * dev:开发环境
 *      * test:测试环境
 *      * prod:生产环境
 */
@Bean
@Profile({
    
    "dev","test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {
    
    
    PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
    performanceInterceptor.setMaxTime(500);//ms,超过此处设置的ms则sql不执行
    performanceInterceptor.setFormat(true);
    return performanceInterceptor;
}

Second step

Configuration in application.properties

#环境设置:dev、test、prod
spring.profiles.active=dev

Conditional query Wrapper

Generally use querywrapper (more powerful)

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-6CmwEtTX-1611036596471) (C:\Users\王东梁\AppData\Roaming\Typora\typora-user-images\ image-20210118220450433.png)]

    public void testSelectQuery() {
    
    
        //创建QueryWrapper对象
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        //通过QueryWrapper设置条件
        //ge、gt、le、lt
        //查询age>=30记录
        //第一个参数字段名称,第二个参数设置值
//        wrapper.ge("age",30);

        //eq、ne
        //wrapper.eq("name","lilei");
        //wrapper.ne("name","lilei");

        //between
        //查询年龄 20-30
        // wrapper.between("age",20,30);

        //like
        //wrapper.like("name","岳");

        //orderByDesc
        // wrapper.orderByDesc("id");

        //last,在最后拼上
        //wrapper.last("limit 1");

        //指定要查询的列
        wrapper.select("id","name");

        List<User> users = userMapper.selectList(wrapper);
        System.out.println(users);

    }

Guess you like

Origin blog.csdn.net/qq_45783660/article/details/112825766