引入Pom
<!--springboot依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.9-rc</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!-- 代码自动生成器依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<version>1.10.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
生成方法
package com.zh;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class CodeGenerator {
private static final String dbName = "mybatis_plus_db";
private static final String driverClassName = "com.mysql.cj.jdbc.Driver";
private static final String dbUrl = "jdbc:mysql://localhost:3306/" + dbName + "?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8";
private static final String dbUsername = "root";
private static final String dbPassword = "root";
private static final String basePackageName = "com.zx";
private static final String entityName = "entity";
private static final String author = "wangyufang";
// 是否开启swagger日志
private static final boolean useSwagger = true;
// 是否覆盖
private static final boolean isOverride = true;
/**
* 获取某个数据库中的所有表名
* @param dbName
* @return
* @throws Exception
*/
private static String[] getTables(String dbName) throws Exception {
List<String> tables = new ArrayList<String>();
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
Class.forName(driverClassName);
connection = DriverManager.getConnection(dbUrl,dbUsername,dbPassword);
String sql = "select table_name from information_schema.tables where table_schema=?";
ps = connection.prepareStatement(sql);
ps.setString(1,dbName);
resultSet = ps.executeQuery();
while (resultSet.next()) {
tables.add(resultSet.getString("table_name"));
}
String[] result = tables.toArray(new String[tables.size()]);
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
throw new Exception("数据库连接异常!");
}
/**
* 直接获取数据库中的所有表名然后自动生成
* 自动生成entity、mapper、service、controller的代码
* @throws Exception
*/
private static void generateAllInfo() throws Exception {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor(author);
gc.setOpen(false);
gc.setSwagger2(useSwagger); //实体属性 Swagger2 注解
gc.setFileOverride(isOverride); // 是否覆盖
gc.setServiceName("%sService"); //去Service的I前缀
gc.setIdType(IdType.ASSIGN_ID); //主键策略
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(dbUrl);
dsc.setDriverName(driverClassName);
dsc.setUsername(dbUsername);
dsc.setPassword(dbPassword);
dsc.setDbType(DbType.MYSQL);
/**
dsc.setTypeConvert(new MySqlTypeConvert(){
@Override
public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType){
if(fieldType.toLowerCase().contains("datetime")){
return addTestEnum("DATE","DateTime","cn.hutool.core.date.DateTime");
}
return (DbColumnType) super.processTypeConvert(globalConfig,fieldType);
}
});
*/
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(null);
pc.setParent(basePackageName);
pc.setEntity(entityName);
pc.setMapper("mapper");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setController("controller");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setChainModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude(getTables(dbName));
strategy.setControllerMappingHyphenStyle(true);
strategy.setLogicDeleteFieldName("is_delete");
strategy.setSuperMapperClass("com.github.yulichang.base.MPJBaseMapper");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
public static void main(String[] args) {
try {
generateAllInfo();
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试SQL
CREATE DATABASE mybatis_plus_db;
USE `mybatis_plus_db`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '用户主键',
`name` varchar(20) DEFAULT NULL COMMENT '用户名字',
`age` int DEFAULT NULL COMMENT '用户年龄',
`version` int DEFAULT '1' COMMENT '乐观锁',
`deleted` int DEFAULT '0' COMMENT '逻辑删除',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1482996505408204804 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;