代码生成器
需要的依赖有:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
1.数据库字段封装类
package com.dss.autoUtil;
import lombok.Data;
/**
* @Description:数据库字段封装类
* @ClassName: ColumnClass
* @author: dongshoushan
* @date: 2018年10月25日 11:16
*/
@Data
public class ColumnClass {
/** 数据库字段名称 **/
private String columnName;
/** 数据库字段类型 **/
private String columnType;
/** 数据库字段首字母小写且去掉下划线字符串 **/
private String changeColumnName;
/** 数据库字段注释 **/
private String columnComment;
}
2.FreeMarkerTemplateUtils读取模板
package com.dss.autoUtil;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import java.io.IOException;
/**
* @Description:
* @ClassName: FreeMarkerTemplateUtils
* @author: dongshoushan
* @date: 2018年10月25日 11:17
*/
public class FreeMarkerTemplateUtils {
private FreeMarkerTemplateUtils(){}
private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);
static{
//这里比较重要,用来指定加载模板所在的路径
CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/templates/"));
CONFIGURATION.setDefaultEncoding("UTF-8");
CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
}
public static Template getTemplate(String templateName) throws IOException {
try {
return CONFIGURATION.getTemplate(templateName);
} catch (IOException e) {
throw e;
}
}
}
3.BeanUtils代码生成器核心
package com.dss.autoUtil;
import freemarker.template.Template;
import org.springframework.util.StringUtils;
import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
/**
* @Description:
* @ClassName: BeanUtils
* @author: dongshoushan
* @date: 2018年10月25日 11:18
*/
public class BeanUtils {
private final String AUTHOR = "dongshoushan";
private final String CURRENT_DATE = getDate();
private final String tableName = "t_module";
private final String tableAnnotation = "角色";
private final String URL = "jdbc:mysql://192.168.2.62:3306/boot_mybatis_demo?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false";
private final String USER = "root";
private final String PASSWORD = "root";
private final String DRIVER = "com.mysql.jdbc.Driver";
private final String basePath = System.getProperty("user.dir") + "/src/main/java/com/dss/";
private final String resourcesPath = System.getProperty("user.dir") + "/src/main/resources/";
private final String EntityName = getSecondUnderLineAndUpperCase(tableName);
private final String lowName = lowerCase(EntityName);
public String lowerCase(String str) {
return str.substring(0, 1).toLowerCase() + str.substring(1);
}
/**
* 连接数据库
* @return
* @throws Exception
*/
public Connection getConnection() throws Exception{
Class.forName(DRIVER);
Connection connection= DriverManager.getConnection(URL, USER, PASSWORD);
return connection;
}
public void generate() {
try {
createBeanService();
createBeanServiceImpl();
createBeanController();
createModel();
createBeanDao();
createBeanXmlDao();
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
}
}
private void createBeanXmlDao() throws Exception {
Connection connection = getConnection();
DatabaseMetaData databaseMetaData = connection.getMetaData();
ResultSet resultSet = databaseMetaData.getColumns(null,"%", tableName,"%");
final String suffix = "Dao.xml";
final String path = resourcesPath+"mapper/I" + EntityName + suffix;
final String templateName = "daoXml.ftl";
File mapperFile = new File(path);
//创建文件
File filePath = new File(resourcesPath+"mapper/");
createFilePath(filePath);
Map<String,Object> dataMap = new HashMap<>(16);
List<ColumnClass> columnList = getColumnList(resultSet);
dataMap.put("model_column",columnList);
generateFileByTemplate(templateName,mapperFile,dataMap);
}
/**
*生成serviceImpl
* @param
*/
private void createBeanServiceImpl() throws Exception {
final String suffix = "ServiceImpl.java";
final String path = basePath+"service/impl/" + EntityName + suffix;
final String templateName = "serviceImpl.ftl";
File mapperFile = new File(path);
//创建文件
File filePath = new File(basePath +"service/impl");
createFilePath(filePath);
Map<String,Object> dataMap = new HashMap<>(16);
generateFileByTemplate(templateName,mapperFile,dataMap);
}
/**
* 生成控制层
* @param
*/
private void createBeanController() throws Exception {
final String suffix = "Controller.java";
final String path = basePath+"controller/" + EntityName + suffix;
final String templateName = "controller.ftl";
File mapperFile = new File(path);
//创建文件
File filePath = new File(basePath +"controller/");
createFilePath(filePath);
Map<String,Object> dataMap = new HashMap<>(16);
generateFileByTemplate(templateName,mapperFile,dataMap);
}
private List<ColumnClass> getColumnList(ResultSet resultSet) throws SQLException {
List<ColumnClass> columnClassList = new ArrayList<>();
ColumnClass columnClass;
while(resultSet.next()){
columnClass = new ColumnClass();
//获取字段名称
columnClass.setColumnName(resultSet.getString("COLUMN_NAME"));
//获取字段类型
columnClass.setColumnType(resultSet.getString("TYPE_NAME"));
//转换字段名称,如 sys_name 变成 SysName
columnClass.setChangeColumnName(lowerCase(replaceUnderLineAndUpperCase(resultSet.getString("COLUMN_NAME"))));
//字段在数据库的注释
columnClass.setColumnComment(resultSet.getString("REMARKS"));
columnClassList.add(columnClass);
}
return columnClassList;
}
/**
* 生成Model实体类文件
*/
private void createModel() throws Exception {
Connection connection = getConnection();
DatabaseMetaData databaseMetaData = connection.getMetaData();
ResultSet resultSet = databaseMetaData.getColumns(null,"%", tableName,"%");
//生成实体类
final String suffix = ".java";
final String path = basePath +"model/"+ EntityName+ suffix;
final String templateName = "entity.ftl";
File mapperFile = new File(path);
//创建文件
File filePath = new File(basePath +"model/");
createFilePath(filePath);
Map<String,Object> dataMap = new HashMap<>(16);
List<ColumnClass> columnList = getColumnList(resultSet);
dataMap.put("model_column",columnList);
generateFileByTemplate(templateName,mapperFile,dataMap);
}
/**
*生成service
* @param
*/
private void createBeanService() throws Exception {
final String suffix = "Service.java";
final String path = basePath+"service/I" + EntityName + suffix;
final String templateName = "service.ftl";
File mapperFile = new File(path);
//创建文件
File filePath = new File(basePath +"service/");
createFilePath(filePath);
Map<String,Object> dataMap = new HashMap<>(16);
generateFileByTemplate(templateName,mapperFile,dataMap);
}
/**
*生成Dao文件
* @param
*/
private void createBeanDao() throws Exception {
final String suffix = "Dao.java";
final String path = basePath+"dao/I" + EntityName + suffix;
final String templateName = "dao.ftl";
File mapperFile = new File(path);
//创建文件
File filePath = new File(basePath +"dao/");
createFilePath(filePath);
Map<String,Object> dataMap = new HashMap<>(16);
generateFileByTemplate(templateName,mapperFile,dataMap);
}
private void generateFileByTemplate(final String templateName,File file,Map<String,Object> dataMap) throws Exception{
Template template = FreeMarkerTemplateUtils.getTemplate(templateName);
FileOutputStream fos = new FileOutputStream(file);
dataMap.put("tableName",tableName);
dataMap.put("EntityName",EntityName);
dataMap.put("author",AUTHOR);
dataMap.put("date",CURRENT_DATE);
dataMap.put("table_annotation",tableAnnotation);
dataMap.put("lowName",lowName);
Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240);
template.process(dataMap,out);
}
/**
* 获取系统时间
*
* @return
*/
public static String getDate() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return simpleDateFormat.format(new Date());
}
public static String getSecondUnderLineAndUpperCase(String str){
str = str.substring(str.indexOf("_")+1);
StringBuffer sb = new StringBuffer();
sb.append(str);
int count = sb.indexOf("_");
while(count!=0){
int num = sb.indexOf("_",count);
count = num + 1;
if(num != -1){
char ss = sb.charAt(count);
char ia = (char) (ss - 32);
sb.replace(count , count + 1,ia + "");
}
}
String result = sb.toString().replaceAll("_","");
return StringUtils.capitalize(result);
}
public static String replaceUnderLineAndUpperCase(String str){
StringBuffer sb = new StringBuffer();
sb.append(str);
int count = sb.indexOf("_");
while(count!=0){
int num = sb.indexOf("_",count);
count = num + 1;
if(num != -1){
char ss = sb.charAt(count);
char ia = (char) (ss - 32);
sb.replace(count , count + 1,ia + "");
}
}
String result = sb.toString().replaceAll("_","");
return StringUtils.capitalize(result);
}
/**
* 创建文件
*
* @param file
*/
public void createFilePath(File file) {
if (!file.exists()) {
System.out.println("创建[" + file.getAbsolutePath() + "]情况:" + file.mkdirs());
} else {
System.out.println("存在目录:" + file.getAbsolutePath());
}
}
}
4.AutoCodeMain启动
package com.dss.autoUtil;
/**
* @Description:
* @ClassName: AutoCodeMain
* @author: dongshoushan
* @date: 2018年10月25日 11:18
*/
public class AutoCodeMain {
public static void main(String[] args){
BeanUtils beanUtils = new BeanUtils();
beanUtils.generate();
}
}