mybatis plus 二(对常见的注解、EntityWrapper、MpGenerator的说明)

前言: 上篇文章简单讲解了mybatis plus的简介以及项目简单集成 -文章地址 ,这篇文章对具体使用,和对强大的代码生成器的讲解。

常用注解

以下是对于实体类的一些常见注解描述:

注解名称 说明
@TableName 实体类的类名和数据库表名映射
@TableId 实体类的主键名称和表中主键名称映射
@TableField 实体类中的成员名称和表中字段名称映射(非主键字段)
@TableLogic 用于定义表的字段进行逻辑删除(非物理删除)
@Version 用于字段实现乐观锁

强大的EntityWrapper

Mybatis-Plus 通过 EntityWrapper(MP 封装的一个查询条件构造器)或者 Condition(继承Wrapper) 来让用户自由的构建查询条件,简单便捷,没有额外的负担, 能够有效提高开发效率,这个时候就可以使用EntityWrapper来达到我们的目的,下面对于EntityWrapper的一些常见的方法解释:

先声明EntityWrapper对象
EntityWrapper() wrapper= new EntityWrapper();

方法名称 说明
wrapper.between(column, val1, val2) value1-val2之间的值
wrapper.notBetween(column, val1, val2) 不在value1-val2之间的值
wrapper.groupBy(columns) 对columns进行分组
wrapper.eq(column, params) 相当于where column=params
wrapper.in(column, value) 相当于sql中的in
wrapper.notIn(column, value) 相当于sql中的notin
wrapper.orderBy(columns, isAsc) 相当于sql中的排序
wrapper.exists(value) 相当于sql中exists查询
wrapper.notExists(value) 相当于sql中not exists查询
wrapper.le(column, params) 小于等于
wrapper. lt (column, params) 小于
wrapper.ge(column, params) 大于等于
wrapper. gt (column, params) 大于
wrapper.like(column, value) 模糊查询 like:’%值%’,notLike:’%值%’,likeLeft:’%值’,likeRight:‘值%’
wrapper.having(sqlHaving, params) 条件过滤

ps:主动调用or()表示紧接着下一个方法不是用and连接!(不调用or()则默认为使用and连接)

使用以上的Wrapper条件构造器,对于一些条件sql基本不需要自己去手写,大大的提高工作效率,这是在代码使用的时候解放了使用xml去写sql,下面就介绍下mybatis-plus强大的生成器,它可以将从实体类一直到controller全部生成,并service继承一个通用的service。

MpGenerator

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

/**
 * <p>
 * 代码生成器演示
 * </p>
 */
public class MpGenerator {
    
    

    public static void main(String[] args) {
    
    
//        assert (false) : "代码生成属于危险操作,请确定配置后取消断言执行代码生成!";
        AutoGenerator mpg = new AutoGenerator();
        // 选择 freemarker 引擎,默认 Velocity
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setAuthor("Iwork");
        // 需要换成你自己的项目地址
        gc.setOutputDir("D:\\workspace\\externalservice-api\\src\\main\\java");
        gc.setFileOverride(false);// 是否覆盖同名文件,默认是false
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setOpen(false);// 配置是否打开目录,false 为不打开(可选)
        //gc.setSwagger2(true);// 实体属性 Swagger2 注解,添加 Swagger 依赖,开启 Swagger2 模式(可选)
        gc.setFileOverride(false);// 重新生成文件时是否覆盖,false 表示不覆盖(可选)
        gc.setIdType(IdType.ASSIGN_ID);// 配置主键生成策略,此处为 ASSIGN_ID(可选)
        /* 自定义文件命名,注意 %s 会自动填充表实体属性! */
        // gc.setMapperName("%sDao");
        // gc.setXmlName("%sDao");
        gc.setServiceName("%sService"); // 生成的service没有“I”
//         gc.setServiceImplName("%sServiceImpl");
//         gc.setControllerName("%sAction");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert() {
    
    
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
    
    
                System.out.println("转换类型:" + fieldType);
                // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setUrl("jdbc:mysql://localhost:3306/iwork_api?useSSL=false&allowPublicKeyRetrieval=true&serverTimeZone=UTC");
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
        strategy.setTablePrefix(new String[] {
    
    ""});// 此处可以修改为您的表前缀,为所有实体类添加@TableName()注解映射相应的表
        strategy.setNaming(NamingStrategy.nochange);// 表名生成策略
        // 需要生成的表
        //strategy.setInclude(new String[] {"api_roperate_alarm_log","user_operate_alarm_log","user_operate_log","sys_user","mywork_warning_needapprove", "mywork_needapprovemsglog","mywork_needapprovemsg","mywork_needapprove","mywork_needapprove","mywork_approve_opinion","mywork_approve_handler","mywork_approve"});
        strategy.setInclude(new String[] {
    
    "hold_approved_list","mywork_approve_opinion"});
        strategy.setDbColumnUnderline(true);
        strategy.setCapitalMode(true);
        strategy.setNaming(NamingStrategy.underline_to_camel);
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定义实体父类
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
        // 自定义实体,公共字段
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // 自定义 com.cnooc.externalservice.mapper 父类
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定义 com.cnooc.externalservice.service 父类
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定义 com.cnooc.externalservice.service 实现类父类
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定义 com.cnooc.externalservice.controller 父类
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // 【实体】是否生成字段常量(默认 false)
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // 【实体】是否为构建者模型(默认 false)
        // public User setName(String name) {this.name = name; return this;}
        // strategy.setEntityBuilderModel(true);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.cnooc.externalservice");
        // pc.setModuleName("test");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        // InjectionConfig cfg = new InjectionConfig() {
    
    
        // @Override
        // public void initMap() {
    
    
        // Map<String, Object> map = new HashMap<String, Object>();
        // map.put("abc", this.getConfig().getGlobalConfig().getAuthor() +
        // "-mp");
        // this.setMap(map);
        // }
        // };
        //
        // // 自定义 xxList.jsp 生成
        // List<FileOutConfig> focList = new ArrayList<>();
        // focList.add(new FileOutConfig("/template/list.jsp.vm") {
    
    
        // @Override
        // public String outputFile(TableInfo tableInfo) {
    
    
        // // 自定义输入文件名称
        // return "D://my_" + tableInfo.getEntityName() + ".jsp";
        // }
        // });
        // cfg.setFileOutConfigList(focList);
        // mpg.setCfg(cfg);
        //
        // // 调整 xml 生成目录演示
//         focList.add(new FileOutConfig("/templates/com.cnooc.externalservice.mapper.xml.vm") {
    
    
//         @Override
//         public String outputFile(TableInfo tableInfo) {
    
    
//         return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
//         }
//         });
//         cfg.setFileOutConfigList(focList);
//         mpg.setCfg(cfg);

        // 关闭默认 xml 生成,调整生成 至 根目录
        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
        //   TemplateConfig tc = new TemplateConfig();
        //  tc.setEntity("com.cnooc.externalservice.entity.java");

        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();

        // 打印注入设置【可无】
        // System.err.println(mpg.getCfg().getMap().get("abc"));
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_44011409/article/details/108249364