mybatis-plus

1.配置

1.1.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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.colleage</groupId>
    <artifactId>education</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>education</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</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
            <scope>test</scope>
        </dependency>

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

        <!--mysql运行时依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

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

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1.2.application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_mybatis_plus?useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=quxin
spring.datasource.password=quxin
# 日志输出
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

2.id自动生成

mybatis-plus默认id使用雪花算法,也可以在实体类上使用@TableId指定

@Data
public class User {
    @TableId(type = IdType.ASSIGN_ID)  // 使用雪花算法
    private Long id;
    private String name;
    private Integer age;
    private String email;
    private Date createTime;
    private Date updateTime;
    private Integer deleted;
}

如果设置为@TableId(type = IdType.AUTO),同时数据库开启自增主键,则使用数据库自增主键
或者在配置文件中修改全局配置:mybatis-plus.global-config.db-config.id-type=assign_id

3.自动填充功能

3.1.在类字段上添加注解:

    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

3.2.实现元对象处理器接口

package com.colleage.education.handler;

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

import java.time.LocalDateTime;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

4.利用version实现乐观锁

实体类version属性上添加注解:

    @Version
    private Integer version;

添加乐观锁插件:

@Configuration
public class MyBatisPlusConfig {
    @Bean
    public OptimisticLockerInterceptor OptimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

5.分页

在配置类中添加分页插件:

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
    @Test
    void testSelectByPage() {
        // 查询前两条数据
        Page<User> page = new Page<>(1, 2);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        Page<User> userPage = userMapper.selectPage(page, null);
        List<User> records = userPage.getRecords();
        records.forEach(System.out::println);
        System.out.println(userPage.getCurrent());
        System.out.println(userPage.getTotal());
        System.out.println(userPage.getPages());  // 总页数
        System.out.println(userPage.hasNext()); // 是否有下一页
        System.out.println(userPage.hasPrevious()); // 是否有上一页
    }

也可以设置查询条件(使用QueryWrapper)

    @Test
    void testSelectByPage() {
        // 查询前两条数据
        Page<Map<String, Object>> page = new Page<>(1, 2);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        // 只查询id与name列
        userQueryWrapper.select("id","name");
        // 没有条件则第二个参数可以传null
        Page<Map<String, Object>> mapPage = userMapper.selectMapsPage(page, userQueryWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        records.forEach(System.out::println);
        System.out.println(mapPage.getCurrent());
        System.out.println(mapPage.getTotal());
        System.out.println(mapPage.getPages());  // 总页数
        System.out.println(mapPage.hasNext()); // 是否有下一页
        System.out.println(mapPage.hasPrevious()); // 是否有上一页
    }

6.设置逻辑删除

字段添加注解:

    @TableLogic
    private Integer deleted;

数据库中对应字段设置类型为tinyint,长度为1(默认:值1代表删除,为0代表未删除)
具体值可以在配置文件中修改:

mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

执行代码:

    @Test
    void testLogicDelete() {
        int i = userMapper.deleteById(1443836654438649857L);    // UPDATE user SET deleted=1 WHERE id=? AND deleted=0 
        System.out.println(i);
        System.out.println(userMapper.selectList(null));    // SELECT id,name,age,email,create_time,update_time,deleted FROM user WHERE deleted=0
    }
posted @ 2021-10-01 10:18  kanaliya  阅读(35)  评论(0)    收藏  举报