这里使用的项目是已经配置好的,之前已经做完mybatis-plus的增删改查测试。
现在进行代码自动生成测试
所以使用代码生成器时只需要编写测试类,将src/main/java下原来自己编写的包都删去
package com.mp.test;
import org.junit.Test;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class test {
/*
* 代码生成
*/
@Test
public void testGenerator() {
// 1.全局配置
GlobalConfig config = new GlobalConfig();
config.setActiveRecord(true)// 是否支持AR
.setAuthor("T")// 作者
.setOutputDir("D:\\mp3\\src\\main\\java")//生成代码文件目录
.setFileOverride(true)// 文件覆盖
.setIdType(IdType.AUTO)//主键自增
.setServiceName("%Service")// 设置生成的service接口的名字的首字母是否为I
.setBaseResultMap(true)
.setBaseColumnList(true);
// 2.数据源配置
DataSourceConfig dsConfig = new DataSourceConfig();
dsConfig.setDbType(DbType.MYSQL)
.setDriverName("com.mysql.jdbc.Driver")
.setUrl("jdbc:mysql://localhost:3306/mp")
.setUsername("root")
.setPassword("123456");
// 3.策略配置
StrategyConfig stConfig = new StrategyConfig();
stConfig.setCapitalMode(true)// 全局大写命名
.setDbColumnUnderline(true)// 指定表名 字段名是否使用下划线
.setNaming(NamingStrategy.underline_to_camel)// 数据库表映射到实体命名策略
.setTablePrefix("tbl_")// 全局前缀设置
.setInclude("tbl_employee");// 对应的表名
// 4.包名策略配置
PackageConfig pkConfig = new PackageConfig();
pkConfig.setParent("com.mp")//父包名即多个包名相同部分,设置父包名后,不同包名只需写不同部分
.setMapper("mapper")//如mapper文件对应的包名为com.mp.mapper
.setEntity("beans")
.setController("controller")
.setService("service").setXml("mapper");
// 5.整合配置
AutoGenerator ag = new AutoGenerator();
ag.setGlobalConfig(config)
.setDataSource(dsConfig)
.setStrategy(stConfig)
.setPackageInfo(pkConfig);
// 6.执行
ag.execute();
}
}
上文提及到的配置,都是自动生成代码的一些基础配置,大家可以按照实际情况,对以上配置进行增加或删除。
整体的项目结构如下图(src/main/java下的包均为自动生成,类未展示出来)