将mysql数据库表通过FreeMarker生成对应的Java文件和对应的mybatis文件。
FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
FreeMarker是免费的,基于Apache许可证2.0版本发布。其模板编写为FreeMarker Template Language(FTL),属于简单、专用的语言。需要准备数据在真实编程语言中来显示,比如数据库查询和业务运算, 之后模板显示已经准备好的数据。在模板中,主要用于如何展现数据, 而在模板之外注意于要展示什么数据。
package com.iteye.injavawetrust.freemarker; import java.io.File; import java.util.List; import java.util.Map; /** * @author InJavaWeTrust */ public class TestFreeMarker { public static void main(String[] args) { // 1.创建目录 Params params = UtilXML.params; UtilFile.initDirName(params); // 2.生成文件 List<Tables> tables = UtilXML.tableList; for (Tables table : tables) { System.out.println(table.getTableName()); String javaClassName = UtilString.capitalize(UtilString .dbNameToVarName(table.getTableName())); Map<Object, Object> map = UtilFreemarker.getTableInfo(table .getTableName()); map.put("title", "InJavaWeTrust"); map.put("author", params.getAuthor()); map.put("createTime", UtilDate.getToday()); map.put("project", params.getProject()); map.put("className", javaClassName); map.put("voClassName", javaClassName); map.put("javapackage", params.getJavapackage()); // 1.po String poName = params.getOsdir() + File.separatorChar + "po" + File.separatorChar + javaClassName + "PO.java"; UtilFreemarker.generateFile(poName, "javapo.ftl", map); // 2.vo String voName = params.getOsdir() + File.separatorChar + "vo" + File.separatorChar + javaClassName + "VO.java"; UtilFreemarker.generateFile(voName, "javavo.ftl", map); // 3.xml String xmlName = params.getOsdir() + File.separatorChar + "xml" + File.separatorChar + javaClassName + ".xml"; UtilFreemarker.generateFile(xmlName, "xml.ftl", map); } } }
package com.iteye.injavawetrust.freemarker; /** * @author InJavaWeTrust */ public class Constants { public static final String DRIVER = UtilXML.dataSource.getDriver(); public static final String URL = UtilXML.dataSource.getUrl(); public static final String USER = UtilXML.dataSource.getUsername(); public static final String PASSWORD = UtilXML.dataSource.getPassword(); }
package com.iteye.injavawetrust.freemarker; /** * @author InJavaWeTrust */ public class DataSource { public String driver; public String url; public String username; public String password; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.iteye.injavawetrust.freemarker; /** * @author InJavaWeTrust */ public class Params { public String osdir; public String javapackage; public String author; public String project; public String getOsdir() { return osdir; } public void setOsdir(String osdir) { this.osdir = osdir; } public String getJavapackage() { return javapackage; } public void setJavapackage(String javapackage) { this.javapackage = javapackage; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getProject() { return project; } public void setProject(String project) { this.project = project; } }
package com.iteye.injavawetrust.freemarker; /** * @author InJavaWeTrust */ public class Tables { public String tableName; public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } }
package com.iteye.injavawetrust.freemarker; import java.text.SimpleDateFormat; import java.util.Date; /** * @author InJavaWeTrust */ public class UtilDate { public static String getToday(){ String result = ""; Date date = new Date(); result = format(date); return result; } public static String format(Date date){ String format = "yyyyMMdd"; SimpleDateFormat fmt = new SimpleDateFormat(format); return fmt.format(date); } }
package com.iteye.injavawetrust.freemarker; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; /** * @author InJavaWeTrust */ public class UtilDB { private static Connection conn = null; private static Statement st = null; private static ResultSet rs = null; private static DatabaseMetaData dmd = null; /** * 链接数据库 * @return */ public static Connection connection() { try { Class.forName(Constants.DRIVER); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } try { conn = DriverManager.getConnection(Constants.URL, Constants.USER, Constants.PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return conn; } /** * 关闭链接 * @param rs * @param st * @param conn */ public static void release(ResultSet rs, Statement st, Connection conn) { try { try { if (null != rs) { rs.close(); } } catch (Exception e) { rs = null; } try { if (null != st) { st.close(); } } catch (Exception e) { st = null; } try { if (null != conn) { conn.close(); } } catch (Exception e) { conn = null; } } finally { rs = null; st = null; conn = null; } } /** * 根据表名查询表中列注释 * @param tableName 表名 * @return List<String> */ public static List<String> getColumnRemarksByTableNameWithList(String tableName) { List<String> columnComments = new LinkedList<String>(); connection(); try { dmd = conn.getMetaData(); rs = dmd.getColumns(null, dmd.getUserName(), tableName, null); while (rs.next()) { columnComments.add(rs.getString("REMARKS")); } } catch (SQLException e) { e.printStackTrace(); } release(rs, st, conn); return columnComments; } /** * 根据表名查询表中列名 * @param tableName 表名 * @return List<String> */ public static List<String> getColumnNameByTableNameWithList(String tableName) { List<String> columnComments = new LinkedList<String>(); connection(); try { dmd = conn.getMetaData(); rs = dmd.getColumns(null, dmd.getUserName(), tableName, null); while (rs.next()) { columnComments.add(rs.getString("COLUMN_NAME")); } } catch (SQLException e) { e.printStackTrace(); } release(rs, st, conn); return columnComments; } /** * 根据表名查询表中列类型 * @param tableName 表名 * @return List<String> */ public static List<String> getColumnTyBypeTableNameWithList(String tableName) { List<String> tableNames = new LinkedList<String>(); connection(); try { dmd = conn.getMetaData(); rs = dmd.getColumns(null, dmd.getUserName(), tableName, null); while (rs.next()) { tableNames.add(rs.getString("TYPE_NAME")); } } catch (SQLException e) { e.printStackTrace(); } release(rs, st, conn); return tableNames; } /** * 得到数据库中所有表名 * @return List<String> */ public static List<String> getTableNames() { List<String> tableNames = new LinkedList<String>(); connection(); try { dmd = conn.getMetaData(); rs = dmd.getTables(null, dmd.getUserName(), null, null); while (rs.next()) { tableNames.add(rs.getString("TABLE_NAME")); } } catch (SQLException e) { e.printStackTrace(); } release(rs, st, conn); return tableNames; } }
package com.iteye.injavawetrust.freemarker; /** * @author InJavaWeTrust */ import java.io.File; public class UtilFile { public static void createDir(String path){ if(null != path && !"".equals(path)){ File file = new File(path); file.mkdirs(); } } public static void initDirName(Params params){ //1.po String poDir = params.getOsdir() + File.separatorChar + "po"; createDir(poDir); //2.vo String voDir = params.getOsdir() + File.separatorChar + "vo"; createDir(voDir); //3.xml String xmlDir = params.getOsdir() + File.separatorChar + "xml"; createDir(xmlDir); } }
package com.iteye.injavawetrust.freemarker; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; /** * @author InJavaWeTrust */ public class UtilFreemarker { /** * 获取表中列并转换成java属性 * @param tableName 表名 * @return list */ public static List<String> getColumnName(String tableName) { List<String> retCol = new LinkedList<String>(); List<String> columns = UtilDB.getColumnNameByTableNameWithList(tableName); for(String column : columns){ retCol.add(UtilString.dbNameToVarName(column)); } return retCol; } /** * 获取表中列 * @param tableName 表名 * @return list */ public static List<String> getColumnNameForMybatis(String tableName) { List<String> retCol = new LinkedList<String>(); List<String> columns = UtilDB.getColumnNameByTableNameWithList(tableName); for(String column : columns){ retCol.add(column); } return retCol; } /** * 得到表中列字段长度最长的列字段 * @param tableName 表名 * @return 最长的列字段 */ public static int getMaxColumnLength(String tableName){ int maxLen = 0; List<String> columns = getColumnNameForMybatis(tableName); for(String column : columns){ if(column.length() > maxLen){ maxLen = column.length(); } } return maxLen; } /** * 得到Java属性字段长度最长的字段长度 * @param tableName 表名 * @return Java属性最长字段长度 */ public static int getMaxJavaPropertyLength(String tableName){ int maxLen = 0; List<String> property = getColumnName(tableName); for(String column : property){ if(column.length() > maxLen){ maxLen = column.length(); } } return maxLen; } /** * 获取表中列注释 * @param tableName 表名 * @return list */ public static List<String> getRemarks(String tableName) { List<String> remarks = new ArrayList<String>(); remarks = UtilDB.getColumnRemarksByTableNameWithList(tableName); return remarks; } /** * 获取表中列类型并转换成java类型 * @param tableName 表名 * @return list */ public static List<String> getColumnType(String tableName) { List<String> retTypes = new ArrayList<String>(); List<String> types = UtilDB.getColumnTyBypeTableNameWithList(tableName); for(String type : types){ retTypes.add(UtilString.dbTypeToJavaType(type)); } return retTypes; } /** * 获取mybatis类型 * @param tableName 表名 * @return list */ public static List<String> getMybatisType(String tableName){ List<String> retTypes = new ArrayList<String>(); List<String> types = UtilDB.getColumnTyBypeTableNameWithList(tableName); for(String type : types){ retTypes.add(UtilString.mybatisType(type)); } return retTypes; } /** * 获取dataModel * @param tableName 表名 * @return Map */ public static Map<Object, Object> getTableInfo(String tableName){ Map<Object, Object> map = new HashMap<Object, Object>(); map.put("columns", getColumnName(tableName)); map.put("mybatisColumns", getColumnNameForMybatis(tableName)); map.put("remarks", getRemarks(tableName)); map.put("columnTypes", getColumnType(tableName)); map.put("mybatisTypes", getMybatisType(tableName)); map.put("maxColumnLength", getMaxColumnLength(tableName)); map.put("maxJavaPropertyLength", getMaxJavaPropertyLength(tableName)); return map; } public static void generateFile(String fileName, String templateName, Map<Object, Object> map){ Configuration config = new Configuration(); config.setDefaultEncoding("UTF-8"); config.setTemplateLoader(new ClassTemplateLoader(UtilFreemarker.class, "/")); config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); try{ BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")); Template template = config.getTemplate(templateName); template.process(map, out); out.close(); }catch(Exception e){ e.printStackTrace(); } } public static Map<Object, Object> getMapInfo(String tableName){ Map<Object, Object> map = new HashMap<Object, Object>(); map = UtilFreemarker.getTableInfo(tableName); return map; } }
package com.iteye.injavawetrust.freemarker; /** * @author InJavaWeTrust */ public class UtilString { /** * 首字母大写 * @param str * @return */ public static String capitalize(String str) { if (null == str) { return null; } else if ("".equals(str)) { return str; } return Character.toTitleCase(str.charAt(0)) + str.substring(1); } /** * 将表中列名去下划线且下划线后首字母大写其他字母小写 * @param columnName 表中列名 * @return java类属性名 */ public static String dbNameToVarName(String columnName) { if (columnName == null) { return null; } StringBuilder fieldName = new StringBuilder(); boolean toUpper = false; for (int i = 0; i < columnName.length(); i++) { char ch = columnName.charAt(i); if (ch == '_') { toUpper = true; } else if (toUpper == true) { fieldName.append(Character.toUpperCase(ch)); toUpper = false; } else { fieldName.append(Character.toLowerCase(ch)); } } return fieldName.toString(); } /** * 将数据库类型转换成java类型 * @param columnType 数据库类型 * @return java类型 */ public static String dbTypeToJavaType(String columnType) { String type = ""; if (columnType == null || columnType.trim().equals("")) { return null; } if (columnType.equals("VARCHAR")) { type = "String"; } else if (columnType.equals("DATE")) { type = "java.util.Date"; } else if (columnType.equals("DATETIME")) { type = "java.util.Date"; } else if (columnType.equals("CHAR")) { type = "String"; } else if (columnType.equals("INT")) { type = "Integer"; } else if (columnType.equals("INT UNSIGNED")) { type = "Integer"; } else if (columnType.equals("TEXT")) { type = "String"; } else if (columnType.equals("MEDIUMBLOB")) { type = "byte[]"; } else if (columnType.equals("DECIMAL")) { type = "java.math.BigDecimal"; } else { System.out.println("columnType[" + columnType + "]"); type = null; } return type; } /** * 将数据库类型转换成mybatis配置文件类型 * @param sqlTypeName 数据库类型 * @return mybatis配置文件类型 */ public static String mybatisType(String sqlTypeName){ String type = ""; if (sqlTypeName == null || sqlTypeName.trim().equals("")) { return null; } if(sqlTypeName.equals("VARCHAR") || sqlTypeName.equals("TEXT")){ type = "VARCHAR"; }else if(sqlTypeName.equals("TINYBLOB") || sqlTypeName.equals("BLOB") || sqlTypeName.equals("MEDIUMBLOB")){ type = "BLOB"; } else if (sqlTypeName.equals("CHAR")) { type = "CHAR"; } else if (sqlTypeName.equals("INT")) { type = "INTEGER"; } else if (sqlTypeName.equals("DATETIME") || sqlTypeName.equals("DATE")) { type = "TIMESTAMP"; } else if (sqlTypeName.equals("DECIMAL")) { type = "DECIMAL"; } else if (sqlTypeName.equals("INT UNSIGNED")) { type = "INTEGER"; } else { System.out.println("sqlTypeName[" + sqlTypeName + "]"); type = null; } return type; } public static String getFileName(String tableName, String flag){ String retName; switch(flag){ case "po" : retName = tableName + "_po"; break; case "vo" : retName = tableName + "_vo"; break; default : retName = null; } return retName; } }
package com.iteye.injavawetrust.freemarker; import java.io.File; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * 解析config.xml * @author InJavaWeTrust */ public class UtilXML { public static Params params = new Params(); public static DataSource dataSource = new DataSource(); public static List<Tables> tableList = new ArrayList<Tables>(); static{ parseXml("F:\injavawetrust\injavawetrust\src\main\resources\config.xml"); } private static void parseXml(String xmlResource){ try { SAXReader reader = new SAXReader(); Document document = reader.read(new File(xmlResource)); Element root = document.getRootElement(); List<Element> elements = root.elements(); for(Element element : elements){ if("params".equals(element.getName())){ List<Element> paramElements = element.elements(); for(Element param : paramElements){ if("osdir".equals(param.getName())){ params.setOsdir(param.attributeValue("value")); }else if("javapackage".equals(param.getName())){ params.setJavapackage(param.attributeValue("value")); }else if("author".equals(param.getName())){ params.setAuthor(param.attributeValue("value")); }else if("project".equals(param.getName())){ params.setProject(param.attributeValue("value")); } } }else if("dataSource".equals(element.getName())){ List<Element> ele = element.elements(); for(Element e : ele){ if("driver".equals(e.getName())){ dataSource.setDriver(e.attributeValue("value")); }else if("url".equals(e.getName())){ dataSource.setUrl(e.attributeValue("value")); }else if("username".equals(e.getName())){ dataSource.setUsername(e.attributeValue("value")); }else if("password".equals(e.getName())){ dataSource.setPassword(e.attributeValue("value")); } } }else if("tables".equals(element.getName())){ List<Element> tables = element.elements(); for(Element table : tables){ if("table".equals(table.getName())){ if("yes".equalsIgnoreCase(table.attributeValue("value"))){ List<String> tableNames = UtilDB.getTableNames(); for(String tableName: tableNames){ Tables t = new Tables(); t.setTableName(tableName); tableList.add(t); } break; }else if("no".equalsIgnoreCase(table.attributeValue("value"))){ continue; } Tables t = new Tables(); t.setTableName(table.attributeValue("value")); tableList.add(t); } } } } } catch (DocumentException e) { e.printStackTrace(); } } public static Params getParams() { return params; } public static void setParams(Params params) { UtilXML.params = params; } public static DataSource getDataSource() { return dataSource; } public static void setDataSource(DataSource dataSource) { UtilXML.dataSource = dataSource; } public static List<Tables> getTableList() { return tableList; } public static void setTableList(List<Tables> tableList) { UtilXML.tableList = tableList; } }
freemarker模板
package ${javapackage}.po; /** * <p>${title}</p> * 类名:${className}PO<br> * 创建人:${author}<br> * 创建时间:${createTime}<br> */ public class ${className}PO { <#list columns as propertyName> /** * ${remarks[propertyName_index]} */ private ${columnTypes[propertyName_index]} ${propertyName}; </#list> <#list columns as propertyName> public ${columnTypes[propertyName_index]} get${propertyName?cap_first}() { return ${propertyName}; } public void set${propertyName?cap_first}(${columnTypes[propertyName_index]} ${propertyName}) { this.${propertyName} = ${propertyName}; } </#list> }
package ${javapackage}.vo; import ${javapackage}.po.${className}PO; /** * <p>${title}</p> * 类名:${className}VO<br> * 创建人:${author}<br> * 创建时间:${createTime}<br> */ public class ${voClassName}VO extends ${className}PO { }
<?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="${project?uncap_first}${className}DAO"> <resultMap id="${className?uncap_first}_base" type="${javapackage}.po.${className}PO"> <#list columns as propertyName> <result property="${propertyName}"${""?right_pad(maxJavaPropertyLength - propertyName?length," ")} column="${mybatisColumns[propertyName_index]}"${""?right_pad(maxColumnLength - mybatisColumns[propertyName_index]?length," ")} jdbcType="${mybatisTypes[propertyName_index]}" /> </#list> </resultMap> </mapper>
config 配置文件
<?xml version="1.0" encoding="UTF-8" ?> <config> <params> <osdir value="F:/injavawetrust/injavawetrust/src/main/java/com/iteye/injavawetrust/freemarker"></osdir> <javapackage value="com.iteye.injavawetrust.freemarker"></javapackage> <author value="InJavaWeTrust"></author> <project value="project"></project> </params> <dataSource> <driver value="com.mysql.jdbc.Driver"></driver> <url value="jdbc:mysql://localhost:3306/scott?useUnicode=true&characterEncoding=utf-8"></url> <username value="root"></username> <password value="root"></password> </dataSource> <tables> <table value="no"></table> <table value="emp"></table> <table value="dept"></table> <table value="bonus"></table> <table value="salgrade"></table> </tables> </config>
数据库表
create table dept( deptno int unsigned auto_increment primary key COMMENT '部门编号', dname varchar(15) COMMENT '部门名称', loc varchar(50) COMMENT '部门所在位置' )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='部门表'; create table emp( empno int unsigned auto_increment primary key COMMENT '雇员编号', ename varchar(15) COMMENT '雇员姓名', job varchar(10) COMMENT '雇员职位', mgr int unsigned COMMENT '雇员对应的领导的编号', hiredate date COMMENT '雇员的雇佣日期', sal decimal(7,2) COMMENT '雇员的基本工资', comm decimal(7,2) COMMENT '奖金', deptno int unsigned COMMENT '所在部门', foreign key(deptno) references dept(deptno) )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='雇员表'; create table salgrade( grade int unsigned COMMENT '工资等级', losal int unsigned COMMENT '此等级的最低工资', hisal int unsigned COMMENT '此等级的最高工资' )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='工资等级表'; create table bonus( ename varchar(10) COMMENT '雇员姓名', job varchar(9) COMMENT '雇员职位', sal decimal(7,2) COMMENT '雇员工资', comm decimal(7,2) COMMENT '雇员资金' )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='工资表';
maven 依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.15</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
运行结果 freemarker.rar 源代码 demo.rar