基于FreeMarker实现代码生成器
一、使用方式:
- 修改 database.properties 配置文件中的 JDBC-URL、userName、password
- 修改模板路径和文件生成路径
- 运行程序,生成代码:运行 Gernerator 类 Main 方法
二、具体代码(本人亲测有效):
1.实体类(Cloumn.class,Table.class)
Cloumn.class
import com.code.constant.TypeConstant;
import com.code.util.StringUtils;
/**
* <p>列实体类</p>
* <p/>
*
*/
public class Cloumn {
private String cloumnName;
private String comment;
private String cloumnType;
public String getCloumnName() {
return cloumnName;
}
public void setCloumnName(String cloumnName) {
this.cloumnName = cloumnName;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCloumnType() {
return cloumnType;
}
public void setCloumnType(String cloumnType) {
this.cloumnType = cloumnType;
}
public String getFieldName() {
return StringUtils.putOffUnderline(this.cloumnName);
}
public String getJavaType() {
return TypeConstant.getJavaType(this.cloumnType);
}
public String getUpperCasecloumnName(){
return StringUtils.captureName(getFieldName());
}
}
Table.class
import com.code.util.StringUtils;
import java.io.Serializable;
import java.util.List;
/**
* <p>表实体类</p>
* <p/>
*
*/
public class Table implements Serializable {
private String tableName;
private String comment;
private List<Cloumn> cloumns;
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public List<Cloumn> getCloumns() {
return cloumns;
}
public void setCloumns(List<Cloumn> cloumns) {
this.cloumns = cloumns;
}
public String getClassName(){
return StringUtils.captureName(StringUtils.putOffUnderline(this.tableName));
}
}
2.constant(Constant.class,TypeConstant.class)
Constant.class
/**
* 路径类
*/
public class Constant {
//模板路径
public static String template_path = "项目路径//resources//ftl";
public static String service_save_path = "E://workspace//test";
public static String servie_impl_save_path = "E://workspace//test";
public static String mapper_save_path = "E://workspace//itrip//test";
public static String model_save_path = "E://workspace//itrip//test";
}
TypeConstant.class
public class TypeConstant {
/***
* 类型常量
*/
private static Map<String, String> typeMap = new HashMap<String, String>();
static {
typeMap.put("BIGINT", "Long");
typeMap.put("INT", "Integer");
typeMap.put("VARCHAR", "String");
typeMap.put("TEXT", "String");
typeMap.put("DATETIME", "Date");
typeMap.put("DECIMAL", "Double");
}
public static void addType(String columnType, String javaType) {
typeMap.put(columnType, javaType);
}
public static String getJavaType(String columnType) {
return typeMap.get(columnType);
}
}
3.handler(MvcHandler.class,TableHandler.class)
MvcHandler.class
import com.code.bean.Table;
import com.code.constant.Constant;
import com.code.util.FreeMarkerUtils;
import com.code.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
public class MvcHandler {
String templateFile = Constant.template_path;
public void executeModule(Table table) {
Map input = new HashMap();
input.put("table", table);
input.put("package", "itrip");
input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
String fileName = table.getClassName() + ".java";
String savePath = Constant.model_save_path;
String templateName = "model";
FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
}
public void executeService(Table table) {
Map input = new HashMap();
input.put("table", table);
input.put("package", "itrip");
input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
String fileName = table.getClassName() + "Service" + ".java";
String savePath = Constant.service_save_path + "//" + StringUtils.lowerName(table.getClassName()) + "//";
String templateName = "service";
FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
}
public void executeServiceImpl(Table table) {
Map input = new HashMap();
input.put("table", table);
input.put("package", "itrip");
input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
String fileName = table.getClassName() + "ServiceImpl" + ".java";
String savePath = Constant.servie_impl_save_path + "//" + StringUtils.lowerName(table.getClassName()) + "//";
String templateName = "serviceImpl";
FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
}
public void executeMapper(Table table) {
Map input = new HashMap();
input.put("table", table);
input.put("package", "itrip");
input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
String fileName = table.getClassName() + "Mapper" + ".xml";
String savePath = Constant.mapper_save_path + "//" + StringUtils.lowerName(table.getClassName()) + "//";
String templateName = "mapper";
FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
}
public void executeClazzMapper(Table table) {
Map input = new HashMap();
input.put("table", table);
input.put("package", "itrip");
input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
String fileName = table.getClassName() + "Mapper" + ".java";
String savePath = Constant.mapper_save_path + "//" + StringUtils.lowerName(table.getClassName()) + "//";
String templateName = "clazzMapper";
FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
}
}
TableHandler.class
import com.code.bean.Cloumn;
import com.code.bean.Table;
import java.sql.*;
import java.util.*;
/**
*
*/
public class TableHandler {
private List<String> tableExceptList = new ArrayList<String>();
private static String DBDRIVER ="com.mysql.jdbc.Driver";
private static String DBURL = "jdbc:mysql://localhost:3306/itripdb?useUnicode=true&characterEncoding=utf-8";
private static String DBUSER = "root";
private static String DBPASS = "123456";
public void addExceptTable(String tableName) {
tableExceptList.add(tableName);
}
private List<Table> queryDataTables() {
DatabaseMetaData dmd = null;
Connection conn = null;
List<Table> tables = new ArrayList<Table>();
try {
Class.forName(DBDRIVER);//1、加载驱动
//2、获取连接对象Connection
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
DatabaseMetaData dbmd = conn.getMetaData();
//3、生成Statment
ResultSet resultSet = dbmd.getTables(null, null, null, new String[]{"TABLE"});
while (resultSet.next()) {
Table table = new Table();
table.setCloumns(new ArrayList<Cloumn>());
String tableName = resultSet.getString("TABLE_NAME");
String remarkes = getCommentByTableName(tableName);
table.setTableName(tableName);
table.setComment(remarkes);
ResultSet rs = dbmd.getColumns(null, "%", tableName, "%");
while (rs.next()) {
Cloumn cloumn = new Cloumn();
cloumn.setCloumnName(rs.getString("COLUMN_NAME"));
cloumn.setComment(rs.getString("REMARKS"));
cloumn.setCloumnType(rs.getString("TYPE_NAME"));
table.getCloumns().add(cloumn);
}
tables.add(table);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return tables;
}
public List<Table> getTables() {
List<Table> dataTableList = queryDataTables();
if (null != dataTableList && dataTableList.size() != 0) {
if (null != tableExceptList && tableExceptList.size() == 0) {
for (String tableName : tableExceptList) {
Iterator<Table> it = dataTableList.iterator();
while (it.hasNext()) {
Table x = it.next();
if (x.getTableName().equals(tableName)) {
it.remove();
}
}
}
}
}
return dataTableList;
}
private static String getCommentByTableName(String tableName) throws Exception {
Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SHOW CREATE TABLE " + tableName);
String comment = null;
if (rs != null && rs.next()) {
comment = parse(rs.getString(2));
}
rs.close();
stmt.close();
conn.close();
return comment;
}
/**
* 返回注释信息
*
* @param all
* @return
*/
private static String parse(String all) {
String comment = null;
int index = all.indexOf("COMMENT='");
if (index < 0) {
return "";
}
comment = all.substring(index + 9);
comment = comment.substring(0, comment.length() - 1);
return comment;
}
}
4.util(FreeMarkerUtils.class,HelloFreeMarker.class,PropertiesUtils.class,StringUtils.class)
FreeMarkerUtils.class
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import java.io.*;
import java.util.Map;
public class FreeMarkerUtils {
private static Template getTemplate(String template_path,String templateFileName){
Configuration configuration = new Configuration();
Template template =null;
try {
configuration.setDirectoryForTemplateLoading(new File(template_path));
configuration.setObjectWrapper(new DefaultObjectWrapper());
configuration.setDefaultEncoding("UTF-8"); //设置编码
//模板文件
template=configuration.getTemplate(templateFileName + ".ftl");
} catch (IOException e) {
e.printStackTrace();
}
return template;
}
public static void genteratorFile(Map<String,String> input,String template_path,String templateFileName,String savePath,String fileName){
Template template=getTemplate(template_path,templateFileName);
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
Writer writer = null;
try {
writer=new OutputStreamWriter(new FileOutputStream(savePath+"\\"+fileName), "UTF-8");
template.process(input, writer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
HelloFreeMarker.class
import java.util.*;
import java.io.*;
import freemarker.template.*;
public class HelloFreeMarker{
private Configuration cfg;
public void init() throws Exception{
//初始化FreeMarker配置
//创建一个Configuration实例
cfg = new Configuration();
//设置FreeMarker的模版文件位置
cfg.setDirectoryForTemplateLoading(new File("templates"));
}
public void process()throws Exception{
Map root = new HashMap();
root.put("name", "FreeMarker!");
root.put("msg" , "您已经完成了第一个FreeMarker的示例");
Template t = cfg.getTemplate("test.ftl");
t.process(root, new OutputStreamWriter(System.out));
}
public static void main(String[] args)throws Exception{
HelloFreeMarker hf = new HelloFreeMarker();
hf.init();
hf.process();
}
}
PropertiesUtils.class
import java.io.InputStreamReader;
import java.util.Properties;
/**
* <p></p>
* search 项目专用的读取配置文件的工具类
* @author XX
* @version v1.0
*
*/
public class PropertiesUtils {
private static Properties props;
/**
* 加载配置文件
*
* @param fileName
*/
private static void readProperties(String fileName) {
try {
props = new Properties();
InputStreamReader inputStream = new InputStreamReader(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName), "UTF-8");
props.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据key读取对应的value
*
* @param key
* @return
*/
public static String get(String fileName,String key) {
readProperties(fileName);
return props.getProperty(key);
}
}
StringUtils.class
public class StringUtils {
/**
* 某位置字母大写
*
* @param name
* @param indx
* @return
*/
public static String captureName(String name, int indx) {
name = name.substring(0, indx) + name.substring(indx, indx + 1).toUpperCase() + name.substring(indx + 1);
return name;
}
/**
* 首字母大写
*
* @param name
* @return
*/
public static String captureName(String name) {
name = name.substring(0, 1).toUpperCase() + name.substring(1);
return name;
}
/***
* 首字母小写
*
* @param name
* @return
*/
public static String lowerName(String name) {
name = name.substring(0, 1).toLowerCase() + name.substring(1);
return name;
}
/***
* 去掉下划线 并用驼峰原则进行转化
*
* @return
*/
public static String putOffUnderline(String columnName) {
StringBuffer fieldNameBuffer = null;
String tempNameArray[] = columnName.split("_");
for (int i = 0; i < tempNameArray.length; i++) {
if (i == 0) {
fieldNameBuffer = new StringBuffer(tempNameArray[i]);
} else {
fieldNameBuffer.append(captureName(tempNameArray[i]));
}
}
return fieldNameBuffer.toString();
}
public static void main(String[] args) {
String a = putOffUnderline("a_bccc_d");
System.out.println(a);
}
}
5.启动类(Genterator.class)
Genterator.class
import com.code.bean.Table;
import com.code.handler.MvcHandler;
import com.code.handler.TableHandler;
import java.util.List;
/**
* <p></p>
* <p/>
*
*/
public class Genterator {
public static void main(String args[]) throws Exception {
TableHandler tableHandler = new TableHandler();
tableHandler.addExceptTable("");//排除某一个表
MvcHandler mvcHandler = new MvcHandler();
List<Table> tableList = tableHandler.getTables();
for (Table table : tableList) {
mvcHandler.executeModule(table);
mvcHandler.executeService(table);
mvcHandler.executeServiceImpl(table);
mvcHandler.executeMapper(table);
mvcHandler.executeClazzMapper(table);
}
}
}
模板文件
clazzMapper.ftl
package cn.${package}.mapper.${lowerClassName};
import cn.${package}.pojo.${table.className};
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface ${table.className}Mapper {
public ${table.className} get${table.className}ById(@Param(value = "id") Long id)throws Exception;
public List<${table.className}> get${table.className}ListByMap(Map<String,Object> param)throws Exception;
public Integer get${table.className}CountByMap(Map<String,Object> param)throws Exception;
public Integer insert${table.className}(${table.className} ${lowerClassName})throws Exception;
public Integer update${table.className}(${table.className} ${lowerClassName})throws Exception;
public Integer delete${table.className}ById(@Param(value = "id") Long id)throws Exception;
}
mapper.ftl
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.${package}.mapper.${lowerClassName}.${table.className}Mapper">
<select id="get${table.className}ById" resultType="cn.${package}.pojo.${table.className}" >
select
<#list table.cloumns as cloumn>
<#if cloumn_has_next>
${cloumn.cloumnName} as ${cloumn.fieldName},
<#else>
${cloumn.cloumnName} as ${cloumn.fieldName}
</#if>
</#list>
from ${table.tableName}
<trim prefix="where" prefixOverrides="and | or">
<if test="id != null">
and id=${r"#{id}"}
</if>
</trim>
</select>
<select id="get${table.className}ListByMap" resultType="cn.${package}.pojo.${table.className}" parameterType="java.util.Map">
select
<#list table.cloumns as cloumn>
<#if cloumn_has_next>
${cloumn.cloumnName} as ${cloumn.fieldName},
<#else>
${cloumn.cloumnName} as ${cloumn.fieldName}
</#if>
</#list>
from ${table.tableName}
<trim prefix="where" prefixOverrides="and | or">
<#list table.cloumns as cloumn>
<#if cloumn_has_next>
<if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
and ${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}}
</if>
</#if>
</#list>
</trim>
order by creationDate desc
<if test="beginPos != null and beginPos!='' and pageSize != null and pageSize !='' ">
limit ${r"#{"}beginPos},${r"#{"}pageSize}
</if>
</select>
<select id="get${table.className}CountByMap" resultType="Integer" parameterType="java.util.Map">
select count(*) from ${table.tableName}
<trim prefix="where" prefixOverrides="and | or">
<#list table.cloumns as cloumn>
<#if cloumn_has_next>
<if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
and ${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}}
</if>
<#else>
<if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
and ${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}}
</if>
</#if>
</#list>
</trim>
</select>
<insert id="insert${table.className}" parameterType="cn.${package}.pojo.${table.className}">
insert into ${table.tableName}(
<#list table.cloumns as cloumn>
<#if cloumn_has_next>
<#if cloumn.cloumnName!='id'>
${cloumn.cloumnName},
</#if>
<#else>
<#if cloumn.cloumnName!='id'>
${cloumn.cloumnName})
</#if>
</#if>
</#list>
values(
<#list table.cloumns as cloumn>
<#if cloumn_has_next>
<#if cloumn.cloumnName!='id'>
${r"#{"}${cloumn.fieldName}},
</#if>
<#else>
<#if cloumn.cloumnName!='id'>
${r"#{"}${cloumn.fieldName}})
</#if>
</#if>
</#list>
</insert>
<update id="update${table.className}" parameterType="cn.${package}.pojo.${table.className}">
update ${table.tableName}
<trim prefix="set" suffixOverrides="," suffix="where id=${r"#{"}id}">
<#list table.cloumns as cloumn>
<#if cloumn_has_next>
<if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}},
</if>
<#else>
<if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}}
</if>
</#if>
</#list>
</trim>
</update>
<delete id="delete${table.className}ById" parameterType="Long">
delete from ${table.tableName} where id = ${r"#{"}id}
</delete>
</mapper>
model.ftl
package cn.${package}.pojo;
import java.io.Serializable;
import java.util.Date;
/***
* ${table.comment}
*/
public class ${table.className} implements Serializable {
<#list table.cloumns as cloumn>
//${cloumn.comment}
private ${cloumn.javaType} ${cloumn.fieldName};
</#list>
//get set 方法
<#list table.cloumns as cloumn>
public void set${cloumn.upperCasecloumnName} (${cloumn.javaType} ${cloumn.javaType}){
this.${cloumn.fieldName}=${cloumn.fieldName};
}
public ${cloumn.cloumnType} get${cloumn.upperCasecloumnName}(){
return this.${cloumn.fieldName};
}
</#list>
}
service.ftl
package cn.${package}.service.${lowerClassName};
import cn.${package}.pojo.${table.className};
import java.util.List;
import java.util.Map;
import java.util.List;
import java.util.Map;
import cn.itrip.common.Page;
/**
* Created by shang-pc on 2015/11/7.
*/
public interface ${table.className}Service {
public ${table.className} get${table.className}ById(Long id)throws Exception;
public List<${table.className}> get${table.className}ListByMap(Map<String,Object> param)throws Exception;
public Integer get${table.className}CountByMap(Map<String,Object> param)throws Exception;
public Integer itriptxAdd${table.className}(${table.className} ${lowerClassName})throws Exception;
public Integer itriptxModify${table.className}(${table.className} ${lowerClassName})throws Exception;
public Integer itriptxDelete${table.className}ById(Long id)throws Exception;
public Page<${table.className}> query${table.className}PageByMap(Map<String,Object> param,Integer pageNo,Integer pageSize)throws Exception;
}
serviceImpl.ftl
package cn.${package}.service.${lowerClassName};
import cn.${package}.mapper.${lowerClassName}.${table.className}Mapper;
import cn.${package}.pojo.${table.className};
import cn.itrip.common.EmptyUtils;
import cn.itrip.common.Page;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import cn.itrip.common.Constants;
@Service
public class ${table.className}ServiceImpl implements ${table.className}Service {
@Resource
private ${table.className}Mapper ${lowerClassName}Mapper;
public ${table.className} get${table.className}ById(Long id)throws Exception{
return ${lowerClassName}Mapper.get${table.className}ById(id);
}
public List<${table.className}> get${table.className}ListByMap(Map<String,Object> param)throws Exception{
return ${lowerClassName}Mapper.get${table.className}ListByMap(param);
}
public Integer get${table.className}CountByMap(Map<String,Object> param)throws Exception{
return ${lowerClassName}Mapper.get${table.className}CountByMap(param);
}
public Integer itriptxAdd${table.className}(${table.className} ${lowerClassName})throws Exception{
${lowerClassName}.setCreationDate(new Date());
return ${lowerClassName}Mapper.insert${table.className}(${lowerClassName});
}
public Integer itriptxModify${table.className}(${table.className} ${lowerClassName})throws Exception{
${lowerClassName}.setModifyDate(new Date());
return ${lowerClassName}Mapper.update${table.className}(${lowerClassName});
}
public Integer itriptxDelete${table.className}ById(Long id)throws Exception{
return ${lowerClassName}Mapper.delete${table.className}ById(id);
}
public Page<${table.className}> query${table.className}PageByMap(Map<String,Object> param,Integer pageNo,Integer pageSize)throws Exception{
Integer total = ${lowerClassName}Mapper.get${table.className}CountByMap(param);
pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
Page page = new Page(pageNo, pageSize, total);
param.put("beginPos", page.getBeginPos());
param.put("pageSize", page.getPageSize());
List<${table.className}> ${lowerClassName}List = ${lowerClassName}Mapper.get${table.className}ListByMap(param);
page.setRows(${lowerClassName}List);
return page;
}
}
test.ftl
<html>
<head>
<title>${name}</title>
</head>
<body>
<p>${msg}</p>
</body>
</html>
database.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/sss?useUnicode=true&characterEncoding=utf-8
user=root
password=root
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.code</groupId>
<artifactId>parent</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
</project>
三、运行效果