自己利用springmybatis进行开发时前期花费了大量的时间去写对应的modelmapperservice文件并想到用freemarker来动态生成对应的JAVA文件
开发思路
其实就是将数据库中的表取出来表名作为类名并把对应的列名取出来作为字段名称然后通过 freemarker定制的模版去生成相关的文件即可
我这里只举例说明如何生成对应的model文件其它的可以直接COPY改改就成示例代码如下
首先定义一个对象SqlColumnData包含两个属性columnName(列名称)columnType(列类型)具体定义如下 :
package orgstudyjobdomain; /** * SqlColumnDatajava Create on 上午:: * * * Copyright (c) by MTA * * @author lmeteor * @Email * @description * @version */ public class SqlColumnData {
private String columnName;
private String columnType;
public String getColumnName()
{
return columnName;
}
public void setColumnName(String columnName)
{
lumnName = columnName;
}
public String getColumnType()
{
return columnType;
}
public void setColumnType(String columnType)
{
lumnType = columnType;
}
}
下面三个方法作用如下
//用来获取指定表的所有列名及类型 public List getColumnDatas(String tableName)//将列名生成对应的field 和 methodpublic String getBeanField(String tableName) throws SQLException//将数据库类型转换成对应的JAVA类型publicString getType(String type)
/**
* 获取指定表的所有列名
*
* @param tableName
* @return
* @throws SQLException
*/
public List getColumnDatas(String tableName)
throws SQLException
{
String sqlColumns = SELECT COLUMN_NAME DATA_TYPE FROM inlumns WHERE table_name =
+ tableName + order by ordinal_position;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
List columnList = new ArrayList()
try
{
conn = sqlDialectgetConn()
pst = connprepareStatement(sqlColumns)
rs = pstexecuteQuery()
while (rsnext())
{
String name = rsgetString()
String type = rsgetString()
type = thisgetType(type)
SqlColumnData cd = new SqlColumnData()
cdsetColumnName(nametoLowerCase())
cdsetColumnType(type)
columnListadd(cd)
}
}
catch ( Exception e )
{
eprintStackTrace()
}
finally
{
try
{
if (conn != null) connclose()
if (pst != null) pstclose()
if (rs != null) rsclose()
}
catch ( SQLException e )
{
eprintStackTrace()
}
}
return columnList;
}
/**
* 将列名生成对应的field 和 method
*
* @param tableName
* @return
* @throws SQLException
*/
public String getBeanField(String tableName) throws SQLException
{
List dataList = getColumnDatas(tableName)
StringBuffer str = new StringBuffer()
StringBuffer getset = new StringBuffer()
for (SqlColumnData d : dataList)
{
String name = dgetColumnName()toLowerCase()
String type = dgetColumnType()
String maxChar = namesubstring( )toUpperCase()
strappend(\r\t)append(private )append(type + )append(
name)append(;\n)
String method = maxChar + namesubstring( namelength())
getsetappend(\r\t)append(public )append(type + )append(
get + method + ()\n\t{\n)
getsetappend(\t\t)append(return this)append(name)append(;\n\t}\n)
getsetappend(\r\t)append(public void )append(
set + method + ( + type + + name + )\n\t{\n)
getsetappend(\t\t)append(this + name + =)append(name)append(
;\n\t}\n)
}
argv = strtoString()
method = getsettoString()
return argv + method;
}
private String argv;
private String method;
/**
* 将数据库类型转换成对应的JAVA类型
*
* @param type
* @return
*/
public String getType(String type)
{
type = typetoLowerCase()
if (charequals(type) || varcharequals(type)
|| nvarcharequals(type))
{
return String;
}
else if (intequals(type))
{
return Integer;
}
else if (bigintequals(type))
{
return Long;
}
else if (timestampequals(type) || dateequals(type)
|| datetimeequals(type))
{
return javasqlTimestamp;
}
else if (decimalequals(type))
{
return Double;
}
else if (imageequals(type))
{
return byte[];
}
else if (smallintequals(type))
{
return int;
}
return null;
}
/**
* 将表名转成class名称
*
* @param tableName
* @return
*/
public String getTableNameToClassName(String tableName)
{
String[] splits = tableNametoLowerCase()split(_)
if (splitslength > )
{
StringBuffer className = new StringBuffer()
for (String split : splits)
{
String tempTableName = splitsubstring( )toUpperCase()
+ splitsubstring()
classNameappend(tempTableName)
}
return classNametoString()
}
else
{
String className = splits[]substring( )toUpperCase()
+ splits[]substring()
return className;
}
}
SQL方面就准备的差不多了现在开始准备对应的模版文件如下
我这里使用的freemarker
package orgstudyjobdomain; import javaioSerializable; /** * ${className?default()}java Create on ${datetime?default()} * * * Copyright (c) by MTA * * @author lmeteor * @Email * @description * @version */ @SuppressWarnings(serial) public class ${className?default()} implements Serializable {
${feilds?default()} }
用freemarker通过模版创建文件
/**
* 创建静态文件
*
* @param templateFileName
*
模板文件名例如/WEBINF/view/tempftl
* @param propMap
*
用于处理模板的属性object映射
* @param htmlFilePath
*
要生成的静态文件的路径例如/WEBINF/view////
* @param htmlFileName
*
要生成的文件名例如l
* @param templateFilePath
*
模版路径
*/
@SuppressWarnings(
{ unchecked })
public static void createHtmlFile(String templateFileName Map propMap
String htmlFilePath String htmlFileName String templateFilePath)
{
try
{
Template t = getFreemarkerCFG(templateFilePath)getTemplate(
templateFileName)
//createDirs(htmlFilePath)
File file = null;
if(StringToolsisEmpty(htmlFileName))file = new File(htmlFilePath)
else file = new File(htmlFilePath + / + htmlFileName)
if(!fileexists())filecreateNewFile()
else filedelete()
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file)UTF))
tprocess(propMap out)
outflush()
outclose()
(文件+htmlFilePath+生成成功)
}
catch ( IOException e )
{
eprintStackTrace()
}
catch ( TemplateException e )
{
eprintStackTrace()
}
}
现在该准备的都准备好了准备开始实际调用如下
/**
* 生成JAVAMODULE文件
* @param tableName
*/
public static void createJavaModuleFile(String tableName)
{
String className = sqlutilgetTableNameToClassName(tableName)
// 生成到指定的目录下
String modelPath = domain\\ + className + java;
Map context = new HashMap()
contextput(className className) //
contextput(tableName tableName)
contextput(datetime DateToolsgetDateTools()format(new Date()))
/****************************** 生成bean字段 *********************************/
try
{
contextput(feilds sqlutilgetBeanField(tableName)) // 生成bean
(请稍侯正在生成Bean属性及GETSET方法)
}
catch ( Exception e )
{
eprintStackTrace()
}
// 生成文件代码/
CreateHtmlcreateHtmlFile(TempBeanftl context PCKPATH+modelPath null TEMPLATE_FILEPATH)
}
大致代码就是这么多我在自己的项目中将这个功能界面化了如下
因为我项目中对SPRING的管理都是用注解完成所以不用去修改springxml文件