![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiYWan5yN0EDO4I2YmBjZ2ADZ2kDOiRWYmFWYxIzNxQTNlFmZh9CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.gif)
“ spring-boot中使用mybatis-plus代码生成器,AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。”
============❤开始阅读❤============
正文内容从这里开始(可直接省略,亦可配图说明)。
============❤本文结束❤============
最近spring-boot/cloud 项目中使用了mybatis-plus持久层框架,但是在开发中发现还是比较让你烦恼是一个个的去建对应的表实体类BaseEntity,BaseMapper,Service,Ctrooller,这些操作实在枯燥乏味而且尤其是实体特别容易由于粗心和手误导致不小心写错变量名,在写完代码测试时发现错误,比较麻烦,影响开发效率。这里mybatis-plus官网是提供了一个代码生成器插件,自从使用了它,效率提高不少!非常推荐使用,学习使用成本低。
mybatis-plus代码生成器的使用
[mybatis-plus官方网站](https://mybatis.plus/)
本文建立在了解mbatis持久层框架基础上。
使用软件环境
jdk 8
2.1.6.RELEASE
Greenwich.SR2
1.18.12
mybatis-plus代码生成器依赖
3.3.2
com.baomidoumybatis-plus-boot-starter${mybatis-plus.version}com.baomidoumybatis-plus-generator${mybatis-plus.version}org.apache.velocityvelocity-engine-core2.2
代码生成器Demo
直接上代码
/**
* TODO mybait-plus代码生成器
*com.baomidoumybatis-plus-boot-starter${mybatis-plus.version}com.baomidoumybatis-plus-generator${mybatis-plus.version}org.apache.velocityvelocity-engine-core2.2
*
* @author: [email protected]
* @since: 2020/7/27 22:05*/public class MyBatisPlusAutoGenerator {/**
*
* 读取控制台内容
*
*
* @param tip 提示信息
* @return 控制台输入信息*/public static String scannerInput(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder sbTips = new StringBuilder();
sbTips.append("正在使用Mybatis-Plus代码生成器!\n");
sbTips.append("请输入需要自动生成的" + tip + ":");
System.out.println(sbTips.toString());if (scanner.hasNext()) {
String inputText = scanner.next();if (StrUtil.isNotEmpty(inputText)) {return inputText;
}
}throw new MybatisPlusException("请输入正确的" + tip + "!");
}private static final String BASE_SRC_ROOT = "/src/main/java/";public void codeGenerate() {// 代码生成器
AutoGenerator mpg = new AutoGenerator();// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
String baseSrc = projectPath + BASE_SRC_ROOT;
gc.setOutputDir(baseSrc);
gc.setAuthor("autoGenerateByMyBatisPlus");
gc.setOpen(true);//生成完代码,打开资源管理器查看// gc.setSwagger2(true); 实体属性 Swagger2 注解 mpg.setGlobalConfig(gc);// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/db_geek?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT");// dsc.setSchemaName("public");// 8.X.X com.mysql.cj.jdbc.Driver // com.mysql.jdbc.Driver
dsc.setDriverName("com.mysql.cj.jdbc.Driver");//数据库驱动
dsc.setUsername("root");//用户名
dsc.setPassword("root");//密码 mpg.setDataSource(dsc);// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("org.demo.springcloud"); //"com.baomidou.ant"//最终生成代码目录为 baseSrc/org/demo/springcloud/moduleName
pc.setModuleName(scannerInput("模块名"));
mpg.setPackageInfo(pc);// 配置模板
TemplateConfig templateConfig = new TemplateConfig();// 配置自定义输出模板//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别// templateConfig.setEntity("templates/entity2.java");// templateConfig.setService();// templateConfig.setController();
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); //使用lombok插件
strategy.setRestControllerStyle(true);//使用@RestController// 公共父类// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");//BaseController// 写于父类中的公共字段// strategy.setSuperEntityColumns("id");
strategy.setInclude(scannerInput("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);// mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute();
}public static void main(String[] args) {new MyBatisPlusAutoGenerator().codeGenerate();
}
}
直接运行该类的main方法执行后在控制台按提示输入
模块名、表名,即可生成相应的代码。
成功生成代码后会自动打开生成的目录文件夹
开始使用
使用自动生成的代码快速完成单表的CURD。CURD是一个数据库技术中的缩写词,一般的项目开发的各种参数的基本功能都是CURD。作用是用于处理数据的基本原子操作。
它代表创建(Create)、更新(Update)、读取(Retrieve)和删除(Delete)操作。
CURD 定义了用于处理数据的基本原子操作。
自动生成代码在Idea中项目结构
直接在controller完成增删改查的操作
@RestController
@RequestMapping("/auto/bs-bank-info")public class BsBankInfoController {
@Resource
BsBankInfoServiceImpl bankInfoService;/**
* 查询列表
* @param bsBankInfo
* @return*/
@PostMapping("list")public Object list(@RequestBody BsBankInfo bsBankInfo){
Wrapper queryWrapper = new QueryWrapper<>(bsBankInfo);return bankInfoService.list(queryWrapper);
}
@PostMapping("listbyPage")public Object listbyPage(@RequestBody BsBankInfo bsBankInfo){
Page pager = new Page(1,1);//这里测试固定了
Wrapper queryWrapper = new QueryWrapper<>(bsBankInfo);return bankInfoService.page(pager ,queryWrapper);
}
@PostMapping("add")public Object add(@RequestBody BsBankInfo bsBankInfo){return bankInfoService.save(bsBankInfo);
}
@PostMapping("update")public Object update(@RequestBody BsBankInfo bsBankInfo){return bankInfoService.updateById(bsBankInfo);
}
@PostMapping("delete")public Object delete(@RequestBody BsBankInfo bsBankInfo){return bankInfoService.remove(new QueryWrapper<>(bsBankInfo));
}
}
上面的代码示例是不是看起非常丝滑,简洁!
到此基本上单表的CURD简单完成了。这里只需要写controller里面写你的业务接口代码,其他部分的都是mybatis-plus代码生成器帮你自动生成的。
总结:
这里我用的是3.X版本,现在用的mybatis-plus还是主要以2.X比较多。2.X和3.X目前我直观了解到是
增删查改的方法名不太一样了
如
2.X insert 、selectList
3.X save、 list
代码生成器的区别
代码生成的实体类
3.X去除注解@TableName,@TableField,@TableId等注解,感觉有点不习惯,好像少点了什么,不知道为什么要这样
3.X 实体类 未继承 Model 了,2.X自动生成是继承,可以直接完成简单增删改操作。