mybatisPlus 常见用法

文章目录

  • mybatisPlus 常见用法
    • 一、自动填充
      • 1.1 处理类
      • 1.2 自动填充抽象类
    • 二、枚举
      • 1.1 注解方式
      • 1.2 实现接口方式
    • 三、分页
      • 3.1 配置 config
      • 3.2 定义统一分页接口
      • 3.3 实现分页接口
      • 3.4 使用
    • 四、读写分离
      • 4.1 方式一
        • 4.1.1 application.yml
        • 4.1.2 pom.xml
      • 4.2 方式二
        • 4.2.1 application.yml
        • 4.2.2 pom.xml
      • 4.3 方式三
        • 4.3.1 application.yml
        • 4.3.2 pom.xml
      • 4.4 方式四
        • 4.4.1 application.yml
        • 4.4.2 pom.xml

mybatisPlus 常见用法

一、自动填充

1.1 处理类

@Slf4j
@Component // 不使用@Component,也可在 config 中,将该类注册为 Bean
public class AutoFillHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("created log");
        String username = "测试";
        // createBy 为 当前用户名
        this.setFieldValByName("createdBy", username, metaObject);
        // createTime 为 当前时间
        this.strictInsertFill(metaObject, "createdTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
        // updateBy 为 当前用户名
        this.setFieldValByName("updatedBy", username, metaObject);
        // updateTime 为 当前时间
        this.strictInsertFill(metaObject, "updatedTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("updated log");
        String username = "测试";
        // updateBy 为 当前用户名
        this.setFieldValByName("updatedBy", username, metaObject);
        // updateTime 为 当前时间
        this.strictUpdateFill(metaObject, "updatedTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
    }
}

1.2 自动填充抽象类

@Data
public abstract class  BaseEntity implements Serializable {
    // 创建人
    @TableField(fill = FieldFill.INSERT)
    private String createdBy;
    // 创建时间
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createdTime;
    // 更新人
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private String updatedBy;
    // 更新时间
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updatedTime;
}

二、枚举

1.1 注解方式

  • 枚举类

    @Getter
    @AllArgsConstructor
    public enum GradeEnum{
        UNKNOWN(0, "未知"),
        SECONDARY(2, "中学"),
        PRIMARY(1, "小学"),
        HIGH(3, "高中");
        @EnumValue
        private final Integer code;
        @JsonValue
        private final String  name;
    }
    
  • 使用

    @Data
    @EqualsAndHashCode(callSuper = false)
    @TableName("t_product")
    public class Product extends BaseEntity {
        @TableId(type = IdType.AUTO)
        private Integer id;
        private GradeEnum grade;
    }
    

1.2 实现接口方式

  • 枚举类

    @AllArgsConstructor
    public enum SexEnum implements IEnum<Integer> {
        MALE(0,"男"),
        FEMALE(1,"女");
    
        private final int value;
        @JsonValue
        private final String label;
    
        @Override
        public Integer getValue() {
            return this.value;
        }
    }
    
  • 使用

    @Data
    @TableName("t_student")
    public class Student {
        @TableId(type = IdType.AUTO)
        private Integer id;
        private SexEnum sex;
    }
    

三、分页

3.1 配置 config

@Configuration
public class PageConfig {
    /**
     * 分页插件
     * @return
     */
    @Bean
    @Primary
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return  interceptor;
    }
}

3.2 定义统一分页接口

public interface AppPage<T> {

    /**
     * 当前页页码
     */
    long getPageNum();

    /**
     * 每页条数
     */
    long getPageSize();

    /**
     * 总条数
     */
    long getTotal();

    /**
     * 总页数
     */
    long getTotalPages();

    /**
     * 分页对象记录
     */
    List<T> getItems();
}

3.3 实现分页接口

@AllArgsConstructor
public class MybatisPageImpl<T> implements AppPage<T> {
    private IPage<T> iPage;

    @Override
    public long getPageNum() {
        return iPage.getCurrent();
    }

    @Override
    public long getPageSize() {
        return iPage.getSize();
    }

    @Override
    public long getTotal() {
        return iPage.getTotal();
    }

    @Override
    public long getTotalPages() {
        return iPage.getPages();
    }

    @Override
    public List<T> getItems() {
        return iPage.getRecords();
    }
}

3.4 使用

  • 直接使用 Mapper
@RestController
public class ProductController {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductService productService;
    
    @GetMapping("page")
    public MybatisPageImpl<Product> page() {
        Page<Product> productPage = new Page<>(1, 2);
        IPage<Product> page = productMapper.selectPage(productPage, null);
        // Service 实现 ServiceImpl 接口
        // IPage page = productService.page(productPage, null);
        return new MybatisPageImpl<>(page);
    }
}

四、读写分离

4.1 方式一

MyBatis-Plus 开发参与者,依赖如下:

dynamic-datasource-spring-boot3-starter

4.1.1 application.yml
server:
  port: 8888

spring:
  datasource:
    dynamic:
      primary: master #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        master: # 数据库 master-0, 包含连接池、驱动、地址、用户名、密码
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3336/test?serverTimezone=UTC
          username: root
          password: 123456

        slave-0: # 数据库 slave-0, 包含连接池、驱动、地址、用户名、密码
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3337/test?serverTimezone=UTC
          username: root
          password: 123456

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4.1.2 pom.xml

<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>3.1.4version>
        <relativePath/> 
    parent>
    
    <properties>
        <maven.compiler.source>17maven.compiler.source>
        <maven.compiler.target>17maven.compiler.target>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.31version>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.5.3.2version>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>dynamic-datasource-spring-boot3-starterartifactId>
            <version>4.2.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.6version>
        dependency>
    dependencies>
project>

4.2 方式二

sharding-jdbc 4

4.2.1 application.yml
server:
  port: 8889
spring:
  sharding-sphere:
    props:
      sql:
        show: true
    datasource:
      names: master-0,slave-0
      master-0: # 数据库 master-0, 包含连接池、驱动、地址、用户名、密码
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3336/test?serverTimezone=UTC
        username: root
        password: 123456

      slave-0: # 数据库 slave-0, 包含连接池、驱动、地址、用户名、密码
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3337/test?serverTimezone=UTC
        username: root
        password: 123456
      # 指定数据库分布情况,数据库里面表分布情况
    sharding:
      master-slave-rules:
        ds0: # 主从关系, 读写分离
          master-data-source-name: master-0
          slave-data-source-names:
            - slave-0
      tables: # 分表规则
        dict:
          actual-data-nodes: ds0.dict   # 这里使用主从关系
          key-generator: # 表中主键生成策略
            column: id           # 分库依赖的列
            type: UUID
          table-strategy: # 分片策略
            inline: # 不支持范围查询
              sharding-column: id
              algorithm-expression: dict
4.2.2 pom.xml

<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.5.RELEASEversion>
        <relativePath/> 
    parent>
    
    <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            
            <dependency>
                <groupId>org.apache.shardingspheregroupId>
                <artifactId>sharding-jdbc-spring-boot-starterartifactId>
                <version>4.1.1version>
            dependency>

            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druidartifactId>
                <version>1.2.13-SNSAPSHOTversion>
            dependency>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <scope>runtimescope>
            dependency>
            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>3.5.3.2version>
            dependency>
    dependencies>
project>

4.3 方式三

shardingsphere 5

4.3.1 application.yml
server:
  port: 8888

spring:
  sharding-sphere:
    props:
      sql:
        show: true
    datasource:
      names: master,slave-0
      master:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3336/test?serverTimezone=UTC
        username: root
        password: 123456
      slave-0:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3337/test?serverTimezone=UTC
        username: root
        password: 123456
    rules:
      readwrite-splitting:
        data-sources:
          ds:
            load-balancer-name: round-robin
            static-strategy:
              # 注意,如果接口有事务,读写分离不生效,默认全部使用主库,为了保证数据一致性
              write-data-source-name: master
              read-data-source-names:
                - slave0
        load-balancers:
          round-robin:
            type: RANDOM #一共三种一种是 RANDOM(随机),一种是 ROUND_ROBIN(轮询),一种是 WEIGHT(权重)
      sharding:
        tables:
          user: # 拥有几个分片表0-3
            actual-data-nodes: ds.user_$->{0..1}
            table-strategy:
              standard:
                sharding-column: id
                sharding-algorithm-name: table-inline # 配置算法
        default-database-strategy:
          standard:
            sharding-column: id
            sharding-algorithm-name: database-inline
        sharding-algorithms:
          table-inline:
            type: HASH_MOD
            props:
              sharding-count: 2
          database-inline:
            type: HASH_MOD
            props:
              sharding-count: 3
4.3.2 pom.xml

<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.5.RELEASEversion>
        <relativePath/> 
    parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.5.3.2version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.2.13-SNSAPSHOTversion>
        dependency>
        <dependency>
            <groupId>org.apache.shardingspheregroupId>
            <artifactId>shardingsphere-jdbc-core-spring-boot-starterartifactId>
            <version>5.2.1version>
        dependency>
        <dependency>
            <groupId>org.yamlgroupId>
            <artifactId>snakeyamlartifactId>
            <version>1.32version>
        dependency>
    dependencies>
project>

4.4 方式四

mybatis-plus 原生开发,商用 mybatis-mate-starter

4.4.1 application.yml
server:
  port: 8888
spring:
  main:
    allow-bean-definition-overriding: true

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

mybatis-mate:
  cert:
    grant:  授予单位
    license: 证书

  sharding:
    health: true # 健康检查
    primary: mysql # 默认数据源
    datasource:
      mysql:
        - key: master0
          cluster: master
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3336/test?serverTimezone=UTC
          username: root
          password: 123456

        - key: slave01
          cluster: slave
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3337/test?serverTimezone=UTC
          username: root
          password: 123456
4.4.2 pom.xml

<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>3.1.4version>
        <relativePath/> 
    parent>

    <properties>
        <java.version>17java.version>
        <maven.compiler.source>17maven.compiler.source>
        <maven.compiler.target>17maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.31version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.5.3.2version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.16version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-mate-starterartifactId>
            <version>1.3.2version>
        dependency>
    dependencies>
project>

你可能感兴趣的:(Spring,#,orm,mybatis,spring)