在SpringBoot项目中使用Mybatis-Plus。
- 引入pom
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.2</version>
</dependency>
<!-- MyBatisPlus依赖,要使用MyBatisPlus就必须导入MyBatisPlus的依赖,因为MyBatisPlus中默认有MyBatis的依赖,所以无需再导入MyBatis的依赖了 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.3.4</version>
</dependency>
<!-- MyBatis代码生成器的模板引擎,这个也许需要导入的,官方的文档是这样写的,velocity引擎是默认的,不需要配置其他东西,比较方便,其他模板引擎也可以使用,还可以自定义模板引擎,具体请看官网,这里我使用的是Freemarker,如果使用velocity可以不依赖freemarker并修改生成代码即可 -->
<!-- <dependency>-->
<!-- <groupId>org.apache.velocity</groupId>-->
<!-- <artifactId>velocity-engine-core</artifactId>-->
<!-- <version>2.3</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.32</version>
</dependency>
- 编写代码
// 配置模板
FastAutoGenerator.create("url", "username", "password")
// 全局配置,生成的代码路径
.globalConfig(builder ->
builder.author("brian7788") // 设置作者
//.enableSwagger() // 开启 swagger 模式
.outputDir("D:\\mybatis-plus-generator-demo\\src\\main\\java\\") // 指定输出目录 最好是绝对路径
)
// 使用Freemarker引擎模板,默认的是Velocity引擎模板
.templateEngine(new FreemarkerTemplateEngine())
// 包配置
.packageConfig(builder -> builder.parent("test.mybatis.plus.AutoCreate")//配置包路径
.entity("entity") // 设置实体包名,默认entity
.service("service") // 设置服务包名,默认service
.serviceImpl("service.Impl") // 设置服务实现类包名,默认service.impl
.controller("controller") // 设置控制器包名,默认controller
.mapper("mapper") // 设置mapper包名,默认mapper
.xml("mapper") // 设置xml包名,默认mapper.xml
.other("others") // 设置自定义文件包名,默认other
.pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\SpringCloudLearning\\SpringBootStudy\\src\\main\\resources\\test\\")) // 设置mapper.xml生成路径
)
// 策略配置
.strategyConfig(builder ->
// 设置需要生成的表名
builder.addInclude("tb_user", "tb_role", "tb_user_role")
)
// 自定义文件输出配置
.injectionConfig(builder -> new InjectionConfig.Builder()
// 自定义配置会被优先输出
// 加载模板文件并指定输出文件
// 模板文件名称最好和自定义文件名称一致,方便管理,同时建议统一使用controller等命令,防止出现错误。
.customFile(Collections.singletonMap("controller.java","template/controller.java"))
.customFile(Collections.singletonMap("entity.java", "template/entity.java"))
.customFile(Collections.singletonMap("mapper.java", "template/mapper.java"))
.customFile(Collections.singletonMap("service.java", "template/service.java"))
.customFile(Collections.singletonMap("serviceImpl.java.ftl", "template/serviceImpl.java"))
.build()
)
/*
.injectionConfig:Mybatisplus-generator 的一个配置项,用于指定要使用的自定义配置。
builder -> new InjectionConfig.Builder():Lambda 表达式,用于创建并返回一个 InjectionConfig.Builder 对象。
.customFile(Collections.singletonMap("controller.java","template/controller.java")):调用 Builder 对象的 .customFile 方法,
用于添加一个自定义的模板文件,键值对 "controller.java" 和 "template/controller.java" 分别表示该模板的文件名和路径。
*/
.execute();
效果展示
Reference
代码生成器(新) | MyBatis-Plus
官网样例MySQLGeneratorTest
FreeMarker 中文官方参考手册
利用Mybatisplus-generator+freemarker编写一个独属于你的springboot代码生成程序
MyBatisPlus代码生成器的使用(超详细)