MyBatis-Plus

1.代码生成

  • 主要依赖

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.2.0</version>
    </dependency>
    
    <!--mp代码生成模板-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    
    <!--mp代码生成器-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.2.0</version>
    </dependency>
    
  • 代码生成

    import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
    import com.baomidou.mybatisplus.core.toolkit.StringPool;
    import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    import com.baomidou.mybatisplus.generator.AutoGenerator;
    import com.baomidou.mybatisplus.generator.InjectionConfig;
    import com.baomidou.mybatisplus.generator.config.*;
    import com.baomidou.mybatisplus.generator.config.po.TableInfo;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class CodeGenerator {
        /**
         * <p>
         * 读取控制台内容
         * </p>
         */
        public static String scanner(String tip) {
            Scanner scanner = new Scanner(System.in);
            StringBuilder help = new StringBuilder();
            help.append("请输入" + tip + ":");
            System.out.println(help.toString());
            if (scanner.hasNext()) {
                String ipt = scanner.next();
                if (StringUtils.isNotEmpty(ipt)) {
                    return ipt;
                }
            }
            throw new MybatisPlusException("请输入正确的" + tip + "!");
        }
    
        public static void main(String[] args) {
            // 代码生成器
            AutoGenerator mpg = new AutoGenerator();
    
            // 全局配置
            GlobalConfig gc = new GlobalConfig();
            String projectPath = System.getProperty("user.dir");
            gc.setOutputDir(projectPath + "/src/main/java");
    //        gc.setOutputDir("D:\\test");
            gc.setAuthor("dragon");
            gc.setOpen(false);
            // gc.setSwagger2(true); 实体属性 Swagger2 注解
            gc.setServiceName("%sService");
            mpg.setGlobalConfig(gc);
    
            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://localhost:3306/test_login?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
            // dsc.setSchemaName("public");
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername("root");
            dsc.setPassword("root");
            mpg.setDataSource(dsc);
    
            // 包配置
            PackageConfig pc = new PackageConfig();
            pc.setModuleName(null);
            //基础包路径
            pc.setParent("com.dragon");
            mpg.setPackageInfo(pc);
    
            // 自定义配置
            InjectionConfig cfg = new InjectionConfig() {
                @Override
                public void initMap() {
                    // to do nothing
                }
            };
    
            // 如果模板引擎是 freemarker
            String templatePath = "/templates/mapper.xml.ftl";
            // 如果模板引擎是 velocity
            // String templatePath = "/templates/mapper.xml.vm";
    
            // 自定义输出配置
            List<FileOutConfig> focList = new ArrayList<>();
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(templatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                    return projectPath + "/src/main/resources/mapper/"
                            + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                }
            });
    
            cfg.setFileOutConfigList(focList);
            mpg.setCfg(cfg);
    
            // 配置模板
            TemplateConfig templateConfig = new TemplateConfig();
    
            templateConfig.setXml(null);
            mpg.setTemplate(templateConfig);
    
            // 策略配置
            StrategyConfig strategy = new StrategyConfig();
            strategy.setNaming(NamingStrategy.underline_to_camel);
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
            strategy.setEntityLombokModel(true);
            strategy.setRestControllerStyle(true);
            strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
            strategy.setControllerMappingHyphenStyle(true);
            //表名前缀
    //        strategy.setTablePrefix("m_");
            mpg.setStrategy(strategy);
            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
            mpg.execute();
        }
    }
    
    

2.实体类注解

  • @TableField("列名")

    @TableField("userName")
    private String userName;
    
  • @TableField(fill = FiledFill.INSERT等枚举)

    自动填充使用

  • @TableName(value = "表名")

    @TableName(value = "user")
    public class User{
        
    }
    
  • @TabelId(type = "主键生成策略")
    这个注解是加在实体类中主键字段上的

    @TableId(type="主键生成策略")
    private Integer id;
    
  • @TableLogic

    逻辑删除字段

3.主键生成策略

  1. IdType.AUTO(自动增长策略)

  2. IdType.ID_WORKER(MP自带策略)

    生成19位值,数字类型使用这种策略,例如Long

  3. IdType.ID_WORKER_STR

    生成19位值,字符串类型使用这种策略

  4. IdType.INPUT(自定义输入策略)

  5. IdType.UUID

    随机唯一值

  6. IdType.ASSIGN_ID(雪花算法)

4.自动填充

  • 创建组件

    import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.ibatis.reflection.MetaObject;
    import org.springframework.stereotype.Component;
    import java.time.LocalDateTime;
    
    @Component
    public class MyMetaObjecthandler implements MetaObjectHandler {
        /**
         * 插入操作,自动填充
         * @param metaObject
         */
        @Override
        public void insertFill(MetaObject metaObject) {
            metaObject.setValue("createTime", LocalDateTime.now());//createTime字段自动填充
            metaObject.setValue("updateTime",LocalDateTime.now());//updateTime字段自动填充
        }
    
        /**
         * 更新操作,自动填充
         * @param metaObject
         */
        @Override
        public void updateFill(MetaObject metaObject) {
            metaObject.setValue("updateTime",LocalDateTime.now());//updateTime字段自动填充
        }
    }
    
  • 实体类

    @TableField(fill = FieldFill.INSERT) //插入时填充字段
    private LocalDateTime createTime;
    
    @TableField(fill = FieldFill.INSERT_UPDATE) //插入和更新时填充字段
    private LocalDateTime updateTime;
    

5.逻辑删除

  • application.yml

    mybatis-plus:
      global-config:
        db-config:
          logic-delete-field: flag  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
          logic-delete-value: 1 # 逻辑已删除值(默认为 1)
          logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
    
    
  • 实体类逻辑删除自动添加注解

    @TableLogic
    private Integer deleted;
    
posted @ 2022-11-06 23:46  DawsonDragon  阅读(16)  评论(0编辑  收藏  举报