基于spring MVC 和 MyBatis 泛型的代码生成模板
简单说明
这块代码生成工具是我抽空的时候方便自己使用而编写的,并不适合其他框架,这里由于项目原有,我并没有上传泛型部份的代码,这套代码是基于 spring Mvc + MyBatis 的,好了 废话不多说看图
我在这里主要贴出 java 部份的代码,源代码我已经上传 在文章底部我会贴出下载地址链接
TableHandle.java(主要处理表字段 与 字段对应java类型的转换)
package web.engine.handle;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.sun.istack.internal.logging.Logger;
import web.engine.dbmanager.DBManager;
/**
* 数据库表处理
* @author lx
*
*/
public class TableHandle {
/**
* 查询表结构语句(表名,表字段,数据类型,是否为主键,字段备注)
*/
private static String column_sql = "select TABLE_NAME,COLUMN_NAME,DATA_TYPE,COLUMN_KEY,COLUMN_COMMENT from information_schema.columns where table_schema ='xxxx' ";
private static String table_sql = "select table_comment from information_schema.tables where table_schema = 'xxxx' ";
private static Logger logger = Logger.getLogger(TableHandle.class);
/**
* 根据表名获取字段
* @param tableName
* @throws SQLException
*/
public static List<TableColumn> getColumns(String tableName) {
logger.info("获取【"+ tableName +"】字段信息");
List<TableColumn> list = new ArrayList<TableColumn>();
DBManager manager = new DBManager();
Connection conn = manager.getConnection();
Statement statement = null;
ResultSet rs = null;
String sql = column_sql + "and table_name = '" + tableName + "'";
try {
statement = conn.createStatement();
rs = statement.executeQuery(sql);
while(rs.next()){
TableColumn c = new TableColumn();
c.setColumnComment(rs.getString("COLUMN_COMMENT"));
c.setColumnKey(rs.getString("COLUMN_KEY"));
c.setColumnName(rs.getString("COLUMN_NAME"));
c.setDataType(rs.getString("DATA_TYPE"));
c.setTableName(rs.getString("TABLE_NAME"));
c.setEntityName(StringUtil.fomatJavaName(rs.getString("COLUMN_NAME")));
c.setJavaType(getJavaType(rs.getString("DATA_TYPE")));
c.setJavaTypeObj(getJavaTypeObj(rs.getString("DATA_TYPE")));
list.add(c);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
manager.closeConn(rs,statement,conn);
}
return list;
}
/**
* 根据表名获取字段
* @param tableName
* @throws SQLException
*/
public static String getTableComment(String tableName) {
logger.info("获取【"+ tableName +"】备注信息");
String tableComment = "";
DBManager manager = new DBManager();
Connection conn = manager.getConnection();
Statement statement = null;
ResultSet rs = null;
String sql = table_sql + "and table_name = '" + tableName + "'";
try {
statement = conn.createStatement();
rs = statement.executeQuery(sql);
while(rs.next()){
tableComment = rs.getString("table_comment");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
manager.closeConn(rs,statement,conn);
}
return tableComment;
}
//public static void main(String[] args) {
//TableHandle handle = new TableHandle();
//String tables[] = new String[]{"sys_user","sys_role"};
//for(int i = 0; i < tables.length; i++){
//System.out.println(handle.getTableComment(tables[i]));
//}
//}
private static String getJavaType(String dataType){
String javaType = "String";
switch (dataType) {
case "datetime":
javaType = "Date";
break;
case "date":
javaType = "Date";
break;
case "int":
javaType = "Integer";
break;
case "timestamp":
javaType = "Date";
break;
case "time":
javaType = "Date";
break;
case "year":
javaType = "Date";
break;
case "bigint":
javaType = "Integer";
break;
case "decimal":
javaType = "Double";
break;
case "double":
javaType = "Double";
break;
case "integer":
javaType = "Integer";
break;
case "float":
javaType = "Double";
break;
case "tinyint":
javaType = "Integer";
break;
case "smallint":
javaType = "Integer";
break;
default:
javaType = "String";
break;
}
return javaType;
}
private static String getJavaTypeObj(String dataType){
String javaType = "java.lang.String";
switch (dataType) {
case "datetime":
javaType = "java.util.Date";
break;
case "date":
javaType = "java.util.Date";
break;
case "int":
javaType = "java.lang.Integer";
break;
case "timestamp":
javaType = "java.util.Date";
break;
case "time":
javaType = "java.util.Date";
break;
case "year":
javaType = "java.util.Date";
break;
case "bigint":
javaType = "java.lang.Integer";
break;
case "decimal":
javaType = "java.lang.Double";
break;
case "double":
javaType = "java.lang.Double";
break;
case "integer":
javaType = "java.lang.Integer";
break;
case "float":
javaType = "java.lang.Double";
break;
case "tinyint":
javaType = "java.lang.Integer";
break;
case "smallint":
javaType = "java.lang.Integer";
break;
default:
javaType = "java.lang.String";
break;
}
return javaType;
}
}
TemplateHandle.java(调用模板 生成java文件)
package web.engine.handle;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import com.sun.istack.internal.logging.Logger;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import web.engine.template.TemplateUtil;
public class TemplateHandle {
private static Logger logger = Logger.getLogger(TemplateHandle.class);
public static Map<String, String> templateMap = new HashMap<String, String>();
static{
templateMap.put("dao", "dao.ftl");
templateMap.put("daoImpl", "daoImpl.ftl");
templateMap.put("daoXml", "daoXml.ftl");
templateMap.put("service", "service.ftl");
templateMap.put("serviceImpl", "serviceImpl.ftl");
templateMap.put("action", "action.ftl");
templateMap.put("model", "model.ftl");
}
/**
* 选择模板文件
* @param key 模板KEY
* @param code ssh,ssm 之类的
* @return 模板
*/
public static Template checkTemplate(String key,String code){
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("utf-8");
String templates = TemplateUtil.class.getClassLoader().getResource("template").getPath();
Template temp = null;
try {
//设置模板文件路径
cfg.setDirectoryForTemplateLoading(new File(templates));
temp = cfg.getTemplate(code + templateMap.get(key));
} catch (IOException e) {
e.printStackTrace();
}
return temp;
}
/**
* 生成文件
* @param entityName 处理后的表名称(sysUser)
* @param path 文件创建绝对路径
* @param key模板KEY[dao,daoXml,daoImpl,service,serviceImpl,action,model] only on
* @param temp模板
* @param map数据
*/
public static void createFiles(String entityName,String path,String key,Template temp,Map<String,Object> map){
try {
File docFiles = new File(path + getFiles(key));
if(!docFiles.exists()){
docFiles.mkdirs();
}
File docFile = new File(path + getFiles(key) + getFileName(entityName,key));
logger.info("创建:" + path + getFiles(key) + getFileName(entityName,key));
Writer docout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
//输出文件
temp.process(map, docout);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取生成文件的名称
* @param entityName 处理后的表名称(sysUser)
* @param key 模板KEY
* @return 文件名称
*/
private static String getFileName(String entityName,String key){
String fileName = "";
switch (key) {
case "dao":
fileName = StringUtil.fomatEntityName(entityName) + "Dao.java";
break;
case "daoXml":
fileName = StringUtil.fomatEntityName(entityName) + "Mapper.xml";
break;
case "daoImpl":
fileName = StringUtil.fomatEntityName(entityName) + "DaoImpl.java";
break;
case "service":
fileName ="I" + StringUtil.fomatEntityName(entityName) + "Service.java";
break;
case "serviceImpl":
fileName = StringUtil.fomatEntityName(entityName) + "ServiceImpl.java";
break;
case "action":
fileName = StringUtil.fomatEntityName(entityName) + "Action.java";
break;
case "model":
fileName = StringUtil.fomatEntityName(entityName) + ".java";
break;
default:
break;
}
return fileName;
}
/**
* 获取生成文件的名称
* @param entityName 处理后的表名称(sysUser)
* @param key 模板KEY
* @return 文件名称
*/
private static String getFiles(String key){
String fileName = "";
switch (key) {
case "dao":
fileName ="mapper//";
break;
case "daoXml":
fileName ="mapper//xml//";
break;
case "daoImpl":
fileName ="mapper//impl//";
break;
case "service":
fileName ="service//";
break;
case "serviceImpl":
fileName ="service//impl//";
break;
case "action":
fileName ="controller//";
break;
case "model":
fileName ="model//vo//";
break;
default:
break;
}
return fileName;
}
}
TemplateInvoke.java(调用处理类)
package web.engine.handle;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sun.istack.internal.logging.Logger;
import freemarker.template.Template;
/**
* 调用处理类
* @author lx
*
*/
public class TemplateInvoke {
private static Logger logger = Logger.getLogger(TemplateInvoke.class);
/**
* 需要生成那些文件
*/
private static final String key[] = new String[]{"daoXml","action","dao","daoImpl","model","service","serviceImpl"};
public static void invoke(String path,String page,String tableName){
logger.info("*************************开始创建对象*************************");
List<TableColumn> list = TableHandle.getColumns(tableName);
Set<String> imps = new HashSet<String>();
TableColumn pkColumn = null;
for(TableColumn c : list){
if(!"String".equals(c.getJavaType())){
imps.add(c.getJavaTypeObj());
}
if(!StringUtil.isEmpty(c.getColumnKey()) && "PRI".equals(c.getColumnKey())){
pkColumn = c;
}
}
String tableComment = TableHandle.getTableComment(tableName);
Map<String,Object> map = new HashMap<String,Object>();
map.put("daoPackage", page);
map.put("tableName", tableName);
map.put("tableComment", tableComment);
map.put("entityName", StringUtil.fomatJavaName(tableName));
map.put("columns", list);
map.put("pkColumn", pkColumn);
map.put("imps", imps);
for(int i = 0; i < key.length; i++){
Template template = TemplateHandle.checkTemplate(key[i], "");
TemplateHandle.createFiles(StringUtil.fomatJavaName(tableName), StringUtil.fomatPage(path, page), key[i], template, map);
}
logger.info("*************************创建对象结束*************************");
}
}
模板文件这里我就不做过多的解释,具体内容请下载源代码,自己去了解
源代码下载地址:https://download.csdn.net/download/qq_35244741/10842369
作者:路西大魔王
原文:https://blog.csdn.net/qq_35244741/article/details/84951812