1、引入依赖
<!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
</dependency>
2、导入生成类
package com.atguigu.eduservice;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;
/**
* @author
* @since 2020/11/26
*/
public class CodeGenerator {
@Test
public void run() {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
GlobalConfig gc = new GlobalConfig();
//String projectPath = System.getProperty("user.dir");
gc.setOutputDir("D:\\Idea_workspace\\guli_parent\\service\\service-edu" + "/src/main/java");
gc.setAuthor("chengw");
gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setIdType(IdType.ID_WORKER_STR); //主键策略
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
gc.setSwagger2(true);//开启Swagger2模式
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost/guli?serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("guli");
dsc.setPassword("chenguangwei");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
//包:com.atguigu.eduservice
pc.setParent("com.atguigu");
pc.setModuleName("eduservice"); //模块名
//包:com.atguigu.eduservice.controller
pc.setController("controller");
//包:com.atguigu.eduservice.entity
pc.setEntity("entity");
//包:com.atguigu.eduservice.service
pc.setService("service");
//包:com.atguigu.eduservice.mapper
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("edu_teacher");//对应数据库表名
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
}
需要根据自己的实际情况修改部分内容:
(1)修改代码标注的作者和生成的代码包所存放的位置
(2)配置数据库:数据库url、用户名、密码
(3)设置生成代码包对应的名称:只需要修改框住两个地方
(4)配置策略:只需要修改对应数据库的表名即可
3、执行run()方法
(1)执行前
(2)执行后
会根据我们指定的包以及数据表生成一系列xxxxcontroller、xxxxentity、xxxxmappper、xxxxservice等方法
(3)随便打开一个方法,可以看到是一个空的结构的类,并指定了注释、注解等
实体类还会根据数据库COMMENT
内容添加相应的注解: