虽然MybatisPlus官网上已经给出了新版本代码生成器的核心依赖和核心代码,但对于没接触过的小伙伴还是比较困难上手😭,本文将展现如何使用MybatisPlus-generator快速生成代码。
目录
1. 所需依赖✅
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
2. 遇到的问题🎐
① Cannot resolve symbol ‘FastAutoGenerator’
也就是FastAutoGenerator类找不到
仔细看了看,明 mybatis-plus-generator 已经导入
这是因为MybatisPlus-generator版本太低导致的,将版本换成 3.5.2 就可以了!
② NoClassDefFoundError:freemarker/template/Configuration
这是由于我们使用了官网提供的代码,上面有使用到Freemarker引擎模板,但是我们自己的依赖里没有加,手动在依赖里加上freemarker即可。
③ java.sql.SQLException: No suitable driver found for jdbc
是由于mysql-connector-java没有导入进依赖中,导入即可(之前用的低版本的,也会报同样的错,不妨试试最新版的)
3. 完整代码✅
/**
* @Description:
* @Author: Hanzao
* @Date: 2022/03/24/22:21
*/
public class FastGenerator {
public static void main(String[] args) {
String url= "jdbc:mysql://localhost:3306/数据库表名?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
String username = "数据库username";
String password = "数据库密码";
FastAutoGenerator.create(url, username, password)
.globalConfig(builder -> {
builder.author("SJQUの魂") // 设置作者
.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("D:\\bala~bala~"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
.moduleName("FATHER") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\bala~bala~~~\\mapper")); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.addInclude("product") // 设置需要生成的表名
.addTablePrefix("t_", "c_"); // 设置过滤表前缀
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
4. 最终结果🎉🎉🎉
运行main方法,控制台正常输出
所有文件都将正常生成