快速上手mybatis plus

首先附上mybatis-plus官方文档
本篇参考官方文档记录spring mvc项目接入mybatis plus的全流程及一些问题的解决方案,建议优先参考官方文档
开始之前,假设数据库已建好并已能正常访问

依赖配置

此处使用maven,gradle参考gradle依赖配置

核心依赖

查看最新版本

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.1.0</version>
</dependency>

!!!注:如之前已引入mybatis相关依赖,请去除,mybatis plus会自行管理

代码生成器相关依赖

如不需要代码生成,请跳过

  • AutoGenerator 查看最新版本

    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-generator</artifactId>
      <version>3.1.0</version>
    </dependency>
    
  • 模版引擎,这里选择freemarker供生成器使用

    <dependency>
       <groupId>org.freemarker</groupId>
       <artifactId>freemarker</artifactId>
       <version>2.3.23</version>
    </dependency>
    
  • lombok,使用注解代替set-get方法

    <dependency>
       <groupId>org.projectlombok</groupId>
       <artifactId>lombok</artifactId>
       <version>1.18.2</version>
       <scope>provided</scope>
    </dependency>
    

代码生成

要使用此功能,需添加代码生成器相关依赖

代码生成器

根据官方代码改了个较为简洁方便适合懒人直接使用的生成器, 如需更多配置可查看官方生成器模版或参考文末附的全配置项自行配置

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;


/**
 * @description: 代码生成器
 * @author: 04637@163.com
 * @date: 2019/3/3
 **/
public class CodeGenerator {

    public static void main(String[] args) {
        // ================= 必须修改的配置 start =================

        // 数据源配置
        String jdbcUrl = "jdbc:mysql://localhost:3306/deva?serverTimezone=Asia/Shanghai&useUnicode=true&useSSL=false&characterEncoding=utf8";
        String jdbcDriver = "com.mysql.cj.jdbc.Driver";
        String jdbcUsername = "root";
        String jdbcPassword = "123456";

        // 父级包名配置
        String parentPackage = "com.ty.mp";

        // 生成代码的 @author 值
        String author = "04637@163.com";

        // 要生成代码的表名配置
        String[] tables = {
                "question_info",
                "answer_info",
                "message_info",
        };

        // ================= 必须修改的配置 end =================




        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(author);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        // 生成完毕后是否打开输出目录
        gc.setOpen(false);
        // 为true时生成entity将继承Model类,单类即可完成基于单表的业务逻辑操作,按需开启
        gc.setActiveRecord(false);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(jdbcUrl);
        dsc.setDriverName(jdbcDriver);
        dsc.setUsername(jdbcUsername);
        dsc.setPassword(jdbcPassword);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        // 父级包名,按需修改
        pc.setParent(parentPackage);
        // 设置模块名, 会在parent包下生成一个指定的模块包
        pc.setModuleName(null);
        mpg.setPackageInfo(pc);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setRestControllerStyle(false);
        strategy.setInclude(tables);
        strategy.setSuperEntityColumns("id");
        // Controller驼峰连字符,如开启,则requestMapping由 helloWorld 变为 hello-world 默认false
        strategy.setControllerMappingHyphenStyle(false);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        // 开启后将使用lombok注解代替set-get方法,false则生成set-get方法
        strategy.setEntityLombokModel(true);
        // 在实体类中移除is前缀
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

执行后会生成这些文件

生成结果
可将生成的xml放到resources目录或者配置xml目录为resource目录方便扫描

配置启用mybatis-plus

mapperScanner配置

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="你的mapper目录"/>
</bean>

sqlSessionFactory配置

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mapperLocations" value="mapper xml的资源路径"/>
</bean>

CRUD接口

mapper CRUD接口

生成的mapper接口会继承BaseMapper接口,查看mapper CRUD接口支持的操作

service CRUD接口

生成的service接口会继承 IService接口,查看service CRUD接口支持的操作

条件构造器

QueryWrapper<TagInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("uk_name", tagName);
TagInfo newTag = tagInfoMapper.selectOne(queryWrapper);

查看条件构造器所有条件写法

分页插件

待更新

问题记录及解决

生成的@Data @Accessors等注解是什么意思?

  • 有了@Data注解就无需再写那些get set方法了
  • @Accessors(chain = true) chain为true时,set方法会return该对象,false时则return void
  • @EqualsAndHashCode(callSuper = false) 会自动生成equals 和 hashCode方法,callSuper = false时不会用super的equals比较

已经有了@Data注解,却不能调用set get方法?

需要安装插件 IDEA为例:
File->settings->Plugins 查找lombok plugin安装

待更新

附:生成器全配置项

GlobalConfig 全局配置项

```
/**
 * 生成文件的输出目录【默认 D 盘根目录】
 */
private String outputDir = "D://";

/**
 * 是否覆盖已有文件
 */
private boolean fileOverride = false;

/**
 * 是否打开输出目录
 */
private boolean open = true;

/**
 * 是否在xml中添加二级缓存配置
 */
private boolean enableCache = false;

/**
 * 开发人员
 */
private String author;

/**
 * 开启 Kotlin 模式
 */
private boolean kotlin = false;

/**
 * 开启 swagger2 模式
 */
private boolean swagger2 = false;

/**
 * 开启 ActiveRecord 模式
 */
private boolean activeRecord = false;

/**
 * 开启 BaseResultMap
 */
private boolean baseResultMap = false;

/**
 * 时间类型对应策略
 */
private DateType dateType = DateType.TIME_PACK;

/**
 * 开启 baseColumnList
 */
private boolean baseColumnList = false;
/**
 * 各层文件名称方式,例如: %sAction 生成 UserAction
 * %s 为占位符
 */
private String entityName;
private String mapperName;
private String xmlName;
private String serviceName;
private String serviceImplName;
private String controllerName;
/**
 * 指定生成的主键的ID类型
 */
private IdType idType;
```

StrategyConfig策略配置项

```
/**
 * 是否大写命名
 */
private boolean isCapitalMode = false;
/**
 * 是否跳过视图
 */
private boolean skipView = false;
/**
 * 数据库表映射到实体的命名策略
 */
private NamingStrategy naming = NamingStrategy.no_change;
/**
 * 数据库表字段映射到实体的命名策略
 * <p>未指定按照 naming 执行</p>
 */
private NamingStrategy columnNaming = null;
/**
 * 表前缀
 */
@Setter(AccessLevel.NONE)
private String[] tablePrefix;
/**
 * 字段前缀
 */
@Setter(AccessLevel.NONE)
private String[] fieldPrefix;
/**
 * 自定义继承的Entity类全称,带包名
 */
@Setter(AccessLevel.NONE)
private String superEntityClass;
/**
 * 自定义基础的Entity类,公共字段
 */
@Setter(AccessLevel.NONE)
private String[] superEntityColumns;
/**
 * 自定义继承的Mapper类全称,带包名
 */
private String superMapperClass = ConstVal.SUPER_MAPPER_CLASS;
/**
 * 自定义继承的Service类全称,带包名
 */
private String superServiceClass = ConstVal.SUPER_SERVICE_CLASS;
/**
 * 自定义继承的ServiceImpl类全称,带包名
 */
private String superServiceImplClass = ConstVal.SUPER_SERVICE_IMPL_CLASS;
/**
 * 自定义继承的Controller类全称,带包名
 */
private String superControllerClass;
/**
 * 需要包含的表名,允许正则表达式(与exclude二选一配置)
 */
@Setter(AccessLevel.NONE)
private String[] include = null;
/**
 * 需要排除的表名,允许正则表达式
 */
@Setter(AccessLevel.NONE)
private String[] exclude = null;
/**
 * 【实体】是否生成字段常量(默认 false)<br>
 * -----------------------------------<br>
 * public static final String ID = "test_id";
 */
private boolean entityColumnConstant = false;
/**
 * 【实体】是否为构建者模型(默认 false)<br>
 * -----------------------------------<br>
 * public User setName(String name) { this.name = name; return this; }
 */
private boolean entityBuilderModel = false;
/**
 * 【实体】是否为lombok模型(默认 false)<br>
 * <a href="https://projectlombok.org/">document</a>
 */
private boolean entityLombokModel = false;
/**
 * Boolean类型字段是否移除is前缀(默认 false)<br>
 * 比如 : 数据库字段名称 : 'is_xxx',类型为 : tinyint. 在映射实体的时候则会去掉is,在实体类中映射最终结果为 xxx
 */
private boolean entityBooleanColumnRemoveIsPrefix = false;
/**
 * 生成 <code>@RestController</code> 控制器
 * <pre>
 *      <code>@Controller</code> -> <code>@RestController</code>
 * </pre>
 */
private boolean restControllerStyle = false;
/**
 * 驼峰转连字符
 * <pre>
 *      <code>@RequestMapping("/managerUserActionHistory")</code> -> <code>@RequestMapping("/manager-user-action-history")</code>
 * </pre>
 */
private boolean controllerMappingHyphenStyle = false;
/**
 * 是否生成实体时,生成字段注解
 */
private boolean entityTableFieldAnnotationEnable = false;
/**
 * 乐观锁属性名称
 */
private String versionFieldName;
/**
 * 逻辑删除属性名称
 */
private String logicDeleteFieldName;
/**
 * 表填充字段
 */
private List<TableFill> tableFillList = null;
```
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值