通过简单引入依赖,编写测试类生成对应表CRUD代码信息
- 依赖引入
MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:
<mybatis-plus-generator.version>3.4.1</mybatis-plus-generator.version>
添加 代码生成器 依赖
<!--MP代码自动生成-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus-generator.version}</version>
</dependency>
添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,
用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,
可以采用自定义模板引擎。
Velocity(默认):
<!-- 模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
- 测试类代码
@ActiveProfiles("local")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class CodeGenerationTest {
@Test
public void gener(){
AutoGenerator autoGenerator = new AutoGenerator();
//全局配置
GlobalConfig gc = new GlobalConfig();
//得到当前项目的路径
String oPath = System.getProperty("user.dir");
//生成文件输出根目录
gc.setOutputDir(oPath + "/src/main/java");
//生成完成后不弹出文件框
gc.setOpen(false);
//文件覆盖
gc.setFileOverride(true);
// 不需要ActiveRecord特性的请改为false
gc.setActiveRecord(false);
// XML 二级缓存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(false);
// 作者
gc.setAuthor("admin");
gc.setSwagger2(true);
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setControllerName("%sController");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setEntityName("%sDo");
autoGenerator.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
//设置数据库类型
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName("com.mysql.jdbc.Driver");
//用户名
dsc.setUsername("admin");
//密码
dsc.setPassword("123456");
//指定数据库
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/hello");
autoGenerator.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
// 需要生成的表 默认是全部
//strategy.setInclude(new String[]{"a","b"});
//strategy.setSuperServiceClass(null);
//strategy.setSuperServiceImplClass(null);
strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
strategy.setEntityLombokModel(true);
//去除表前缀
strategy.setTablePrefix("an_");
//去除字段前缀
strategy.setFieldPrefix("");
autoGenerator.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
//父包路径
pc.setParent("com.a.api");
pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setMapper("mapper");
pc.setEntity("db");
pc.setXml("mapper");
autoGenerator.setPackageInfo(pc);
// 执行生成
autoGenerator.execute();
}
}