前言
在Maven项目或者SpringBoot项目中使用该代码生成器可生成controller、mapper、pojo、service,同时还会生成相应mapper.class的xml文件。
一、配置好要生成的数据库和表,以下是我要引用的表
二、创建Maven或者Sping项目加入对应的依赖,配置类
pom.xml(依赖)
<!--连接数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<!-- MyBatis-Plus代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!--@test-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.4.1</version>
<scope>compile</scope>
</dependency>
三、在项目下创建一个create包,添加一个配置类CodeGenerator:
CodeGenerator.class
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:\\Java_project\\mybatistPlusTest" + "/src/main/java");//绝对路径
/*gc.setOutputDir(projectPath + "/src/main/java");//相对路径*/
gc.setAuthor("lsj");
gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
/*IUserService*/
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setIdType(IdType.ID_WORKER); //主键策略
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
//MySQL8.0版本以上写法
dsc.setUrl("jdbc:mysql://localhost:3306/easybuy?serverTimezone=GMT%2B8&useSSL=false");
//MySQL8.0版本以下的写法
/*dsc.setUrl("jdbc:mysql://localhost:3306/easybuy?characterEncoding=utf8");*/
dsc.setDriverName("com.mysql.cj.jdbc.Driver");//MySQL8.0版本以下的不加cj
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com");
pc.setModuleName("lsj"); //模块名
pc.setController("controller");
pc.setEntity("pojo");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("easybuy_car_detail");//该数据库表名
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setTablePrefix("easybuy_"); //生成实体时去掉表前缀
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();
}
}
四、运行CodeGenerator.class自动生成代码
这里的mapper.xml我是习惯放在resource里使用的,放在哪里看个人习惯。
结果如图:
文件里面的注解都是基于MyBatis-Plus + Springboot,不需要的可以自行删除。
以上就是基于MyBatis-Plus的代码生成器的使用。