Mybatis-Plus,个人觉得用与不用差别并不大,不觉得它能帮我们提升多大的效率。
Mybatis自身也提供代码生成器,使用代码生成器快速生成一些通用且常用的Sql也能替代Mybatis-Plus的BaseMapper。只不过Mybatis-Plus它生成的Mapper和xml文件更简洁。
在使用DDD领域驱动设计的经典四层架构后,Mybatis-Plus提供的其它的特性基本不用了。
我最想吐槽的还是Mybatis-Plus的代码生成器,强行给我生成Service、ServiceImpl、Controller,也不问问我有没有需要,一开始以为不配置就不会生成,结果是我天真了。
不说其它的,为每个Mapper都生成一个Service真的有必要吗?我们什么时候开始习惯一个表对应一个Service了。
生成的这些额外类,在DDD四层架构的项目中更是显得多余,笔者还是忍受不了,于是自己改写模板生成引擎,去掉了烦人的Service、ServiceImpl、Controller。
easy-mybatis-plus-generator
easy-mybatis-plus-generator是笔者基于mybatis-plus-generator改造的mybatis-plus代码生成器,其实就是替换了AbstractTemplateEngine抽象模版引擎。
easy-mybatis-plus-generator作为easymulti-datasource-spring-boot-starter的一个子模块。
github链接:github.com/wujiuye/eas…
使用easy-mybatis-plus-generator的前提
- 1、想通过配置文件配置方式使用;
- 2、不想生成
Service、ServiceImpl、Controller类; - 3、接受使用一些默认配置:为
xml文件自动生成baseResultMap、不开启二级缓存、使用lombok、列名自动驼峰映射;
关于版本号
2.x版本:对应mybatis-plus3.x版本,也对应mybatis-plus-generator3.x版本,最新版本:2.0.1-RELEASE;
使用方式
- 第一步:添加依赖
<!-- easy-mybatis-plus-generator -->
<dependency>
<groupId>com.github.wujiuye</groupId>
<artifactId>easy-mybatis-plus-generator</artifactId>
<version>2.0.1-RELEASE</version>
</dependency>
当然,还需要数据库的jdbc驱动包,比如mysql
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
<scope>runtime</scope>
</dependency>
- 第二步:添加配置
在
resources目录下添加mybatis-plus-generator.properties配置文件,配置项如下
### 数据源配置
datasource.jdbc.url=
datasource.jdbc.driverName=com.mysql.jdbc.Driver
datasource.jdbc.username=
datasource.jdbc.password=
### 全局配置
globalconfig.author=mybatis-plus
globalconfig.outputDir=easy-mybatis-plus-generator/test/src/main/java
globalconfig.entityName=%sPO
globalconfig.mapperName=%sMapper
globalconfig.xmlName=%sMapper
- 第三步:编写代码
编写测试类,或者编写一个main方法,调用EasyMybatisGenerator#run方法生成代码,代码如下。
public class EasyGeneratorTest {
public static void main(String[] args) throws Exception {
// 配置包信息
PackageConfig config = new PackageConfig()
.setParent("com.github.wujiuye.generator")
.setEntity("repo.dao.po")
.setMapper("repo.dao")
.setXml("repo.dao");
// 开始生成代码
EasyMybatisGenerator.run(config,"pay_config_rec");
}
}
EasyMybatisGenerator#run方法参数说明:
packageConfig:生成的Entity、Mappper的包信息,同时也是生成的Entity、Mappper、Xml文件的输出路径;tables:此次需要自动生成代码的数据库表的名称;