MyBatis-Plus(使用总结)

MyBatis-Plus是一个MyBatis的增强工具,提供了便捷的CRUD操作和代码生成器。通过配置,可以实现自动注入、性能优化和分页插件等功能。同时,它支持Lambda表达式的条件构造器,便于进行复杂查询。此外,MyBatis-Plus还支持逻辑删除,使得数据管理更加灵活。
摘要由CSDN通过智能技术生成

Mybatis-plus


MyBatis-Plus简介

Mybatis-Plus是一款MyBatis的增强工具包,简化 CRUD 操作。启动加载 XML 配置时注入单表 SQL 操作 ,为简化开发工作、提高生产率而生。Mybatis-Plus 启动注入非拦截实现、性能更优,让你专注业务快速敏捷开发。

文档 http://mp.baomidou.com

http://mybatis.plus

https://gitee.com/baomidou/mybatis-plus

https://gitee.com/baomidou/mybatis-plus-samples/tree/master


1.开发准备
1.依赖
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>
<!--代码生成器-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>
2.代码生成器:
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.setAuthor("woniuxy");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mydb?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.woniuxy");
        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/" + pc.getModuleName()
                        + "/" + 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.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
3.MyBatis-Plus配置
mybatis-plus:
  mapper-locations: classpath*:mapper/*.xml
  type-aliases-package: com.woniuxy.sys.entity
  configuration:
    map-underscore-to-camel-case: true
4.分页插件配置
@Configuration
public class MybatisPlusConfig {
    /**
     * MyBatis-Plus分页插件
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
2.常用注解
@TableName:数据库表相关
@TableId:表主键标识
@TableField:表字段标识
@TableLogic:表字段逻辑处理注解(逻辑删除)
@TableId(type= IdType.ID_WORKER_STR)
@TableField(exist = false):表示该属性不为数据库表字段,但又是必须使用的。
@TableField(exist = true):表示该属性为数据库表字段。
@TableField(condition = SqlCondition.LIKE):表示该属性可以模糊搜索。
@TableField(fill = FieldFill.INSERT):注解填充字段 ,生成器策略部分也可以配置!
3.Mapper CRUD 接口
  • insert
  • delete
  • update
  • select
4.条件构造器
  • eq
  • like
  • between
  • in
  • inSql
5.lambda条件构造器
  • LambdaQueryWrapper
  • LambdaQueryChainWrapper
6.condition条件
7.自动填充
  • 第一步在实体属性上添加注解

    @TableField(fill = FieldFill.INSERT)
    @TableField(fill = FieldFill.UPDATE)
    
  • 定义填充处理器,实现元对象处理器接口

    @Component
    public class CustomMetaObjectHandler implements MetaObjectHandler {
        @Override
        public void insertFill(MetaObject metaObject) {
            Object value = getFieldValByName("createTime",metaObject);
            if(value == null){
                 strictInsertFill(metaObject,"createTime", Date.class, new Date());
            }
        }
        @Override
        public void updateFill(MetaObject metaObject) {
            Object value = getFieldValByName("modifyTime",metaObject);
            if(value == null){
                strictUpdateFill(metaObject,"modifyTime",Date.class,new Date());
            }
        }
    }
    
8.逻辑删除
  • 配置yml

    mybatis-plus:
      global-config:
        db-config:
          logic-delete-value: 1   # 逻辑未删除的值
          logic-not-delete-value: 0  #逻辑已删除的值
    
  • 属性添加注解

    @TableLogic
    
  • 设置逻辑删除后,在执行查询及更新语句是会自动过滤条件;而自定义查询则不会添加过滤条件,需要手动指定条件。

  • 查询结果中排除删除字段

    @TableField(select=false)
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值