自己写了一个自动生成源代码的工具,代码自动生成,以及一个完整项目的成功实践,还在继续完善当中,采用freemaker配置模板,可以根据自己的需要生成自己想要的代码
先来看看怎么使用,很简单
先配置config.xml 配置设置模板路径,以及项目生成路径,可以自己定义
<?xml version="1.0" encoding="UTF-8"?> <xml-body> <code> <projectpath>D:/vobuilder/vobuilder</projectpath> <model>com.hyj.model</model> <action>com.hyj.action</action> <dao>com.hyj.dao</dao> <daoimpl>com.hyj.dao.jdbc</daoimpl> <service>com.hyj.service</service> <serviceimpl>com.hyj.service.impl</serviceimpl> <jsp>/freemarker/jsp</jsp> </code> </xml-body>
CodeGenerator cg = new CodeGenerator(); cg.generate("tableName"); //这样就生成了所有项目的文件
1.生成代码的引擎
package com.hyj.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.sql.Connection; import java.util.Map; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import com.szxhdz.util.Factory; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; public abstract class AbstractEngine { protected static Logger logger = LogManager.getLogger(AbstractEngine.class); protected static Connection con; protected static Configuration cfg; public AbstractEngine(String templatePath) { con = Factory.getConnection(); try { cfg = new Configuration(); cfg.setDefaultEncoding("gb2312"); cfg.setDirectoryForTemplateLoading(new File(templatePath)); cfg.setObjectWrapper(new DefaultObjectWrapper()); } catch (Exception e) { e.printStackTrace(); } } public static void create(String ftlTemplate, Map contents, String savePath, String saveFilename) { try { Template temp = cfg.getTemplate(ftlTemplate); logger.info("generate file " + saveFilename + " in path " + savePath); File file = new File(savePath); if (!file.exists()) { file.mkdirs(); } Writer out = new OutputStreamWriter(new FileOutputStream(savePath + "/" + saveFilename), "gb2312"); temp.process(contents, out); out.flush(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e1) { e1.printStackTrace(); } } }
2。生成代码的实现类
package com.hyj.util; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.hyj.util.JDBCUtil.Column; import com.szxhdz.util.SystemConstant; public class CodeGenerator extends AbstractEngine implements Creater{ private static final String BASE_PATH = SystemConstant.getProperty("code.projectpath"); private static final String PACKAGE_PATH = "/src/com/hyj/"; private static final String JAVA_CODE_GENERATOR_PATH = BASE_PATH + PACKAGE_PATH; private static final String TEMPLATE_PATH = BASE_PATH + "/freemarker/template"; public CodeGenerator() { super(TEMPLATE_PATH); } public CodeGenerator(String templatePath) { super(templatePath); } public void generatorJSP(String table) { try { List priList = JDBCUtil .getPrimaryKeyColumns(con, null, null, table); Column pk = (Column) priList.get(0); Map params = new HashMap(); params.put("table", table); params.put("columnList", JDBCUtil.getTableColumns(con, null, null, table)); params.put("pk", pk); create("add.ftl", params, BASE_PATH + "/freemarker/jsp", table .toLowerCase().replaceAll("_", "") + "_add.jsp"); } catch (Exception e) { e.printStackTrace(); } } public void generaorAll() { List tbList = null; try { tbList = JDBCUtil.getTables(con, null, "FTFJ_WEB", null); for (Iterator iter = tbList.iterator(); iter.hasNext();) { String table = (String) iter.next(); generatorJSP(table); } } catch (SQLException e) { e.printStackTrace(); } } public void generateModel(String table) { try { Map params = new HashMap(); params.put("table", table); params.put("columnList", JDBCUtil.getTableColumns(con, null, null, table)); create("bean.ftl", params, JAVA_CODE_GENERATOR_PATH + "model", table.substring(0, 1).toUpperCase() + table.toLowerCase().replaceAll("_", "") .substring(1) + ".java"); } catch (Exception e) { e.printStackTrace(); } } public void generatorModels() { List tbList = null; try { tbList = JDBCUtil.getTables(con, null, "FTFJ_WEB", null); for (Iterator iter = tbList.iterator(); iter.hasNext();) { String table = (String) iter.next(); generateModel(table); } } catch (SQLException e) { e.printStackTrace(); } } public void generateDao(String tableName) { try { List priList = JDBCUtil .getPrimaryKeyColumns(con, null, null, tableName); Column pk = (Column) priList.get(0); Map params = new HashMap(); params.put("tableName", tableName); params.put("columnList", JDBCUtil.getTableColumns(con, null, null, tableName)); params.put("pk", pk); create("dao.ftl", params, BASE_PATH +"/src/"+ SystemConstant.getProperty("code.dao").replace(".","/"),"I"+ tableName .substring(0, 1).toUpperCase() + tableName.substring(1,tableName.length()).toLowerCase() .replaceAll("_", "") + "Dao.java"); } catch (Exception e) { e.printStackTrace(); } } public void generateDaoImpl(String table) { try { List priList = JDBCUtil .getPrimaryKeyColumns(con, null, null, table); Column pk = (Column) priList.get(0); Map params = new HashMap(); params.put("table", table); params.put("columnList", JDBCUtil.getTableColumns(con, null, null, table)); params.put("pk", pk); create("daoimpl.ftl", params, JAVA_CODE_GENERATOR_PATH + "dao/jdbc", table .substring(0, 1).toUpperCase() + table.substring(1, table.length()).toLowerCase() .replaceAll("_", "") + "Dao.java"); } catch (Exception e) { e.printStackTrace(); } } public void generateSql() { List tbList = null; List ls = new ArrayList(); try { tbList = JDBCUtil.getTables(con, null, null, null); Map params = new HashMap(); for (Iterator iter = tbList.iterator(); iter.hasNext();) { String table = (String) iter.next(); List columnlist = JDBCUtil.getTableColumns(con, null, null, table); Column pk = (Column) JDBCUtil.getPrimaryKeyColumns(con, null, null, table).get(0); SqlBean sqlbean = new SqlBean(); sqlbean.setColumnList(columnlist); sqlbean.setPk(pk); sqlbean.setTable(table); ls.add(sqlbean); } params.put("ls", ls); create("db.ftl", params, JAVA_CODE_GENERATOR_PATH + "sql", "db.sql"); } catch (SQLException e) { e.printStackTrace(); } } public void generateAction(String table) { try { Map params = new HashMap(); List columnlist = JDBCUtil.getTableColumns(con, null, null, table); params.put("columnlist", columnlist); params.put("table", table); params.put("pk", JDBCUtil.getPrimaryKeyColumns(con, null, null, table).get(0)); create("action.ftl", params, JAVA_CODE_GENERATOR_PATH + "action", table.substring(0, 1).toUpperCase() + table.substring(1).toLowerCase().replaceAll("_", "") + "Action.java"); } catch (Exception e) { e.printStackTrace(); } } public void generateList(String table) { try { Map params = new HashMap(); List columnlist = JDBCUtil.getTableColumns(con, null, null, table); params.put("columnlist", columnlist); params.put("table", table); params.put("pk", JDBCUtil.getPrimaryKeyColumns(con, null, null, table).get(0)); create("list.ftl", params, BASE_PATH + "/freemarker/jsp", table .toLowerCase().replaceAll("_", "") + "_list.jsp"); } catch (Exception e) { e.printStackTrace(); } } public void generateXwork(String table) { try { Map params = new HashMap(); List columnlist = JDBCUtil.getTableColumns(con, null, null, table); params.put("columnlist", columnlist); params.put("table", table); params.put("pk", JDBCUtil.getPrimaryKeyColumns(con, null, null, table).get(0)); create("xwork.ftl", params, JAVA_CODE_GENERATOR_PATH, "xwork-" + table.toLowerCase().replaceAll("_", "") + ".xml"); } catch (Exception e) { e.printStackTrace(); } } public void generateApplicationContext() { List tbList = null; List tableList = new ArrayList(); try { tbList = JDBCUtil.getTables(con, null, null, null); for (Iterator iter = tbList.iterator(); iter.hasNext();) { String table = (String) iter.next(); tableList.add(table); } Map params = new HashMap(); params.put("tableList", tableList); create("applicationContext.ftl", params, JAVA_CODE_GENERATOR_PATH, "applicationContext.xml"); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void generateValidation(String table) { try { Map params = new HashMap(); List columnlist = JDBCUtil.getTableColumns(con, null, null, table); params.put("columnlist", columnlist); params.put("table", table); params.put("pk", JDBCUtil.getPrimaryKeyColumns(con, null, null,table).get(0)); create("validation.ftl", params, JAVA_CODE_GENERATOR_PATH + "action",table.substring(0,1).toUpperCase()+table.substring(1).toLowerCase().replaceAll("_", "") + "Action-validation.xml"); } catch (Exception e) { e.printStackTrace(); } } public void generateValidation_properties(String table) { try { Map params = new HashMap(); List columnlist = JDBCUtil.getTableColumns(con, null, null, table); params.put("columnlist", columnlist); params.put("table", table); params.put("pk", JDBCUtil.getPrimaryKeyColumns(con, null, null,table).get(0)); create("validation_properties.ftl", params, JAVA_CODE_GENERATOR_PATH + "action",table.substring(0,1).toUpperCase()+table.substring(1).toLowerCase().replaceAll("_", "") + "Action.properties"); } catch (Exception e) { e.printStackTrace(); } } public void generateService(String tableName) { try { Map params = new HashMap(); List columnlist = JDBCUtil.getTableColumns(con, null, null, tableName); params.put("columnlist", columnlist); params.put("tableName", tableName); params.put("pk", JDBCUtil.getPrimaryKeyColumns(con, null, null,tableName).get(0)); create("service.ftl", params, BASE_PATH+"/src/" + SystemConstant.getProperty("code.service").replace(".","/"),"I"+tableName.substring(0,1).toUpperCase()+tableName.substring(1).toLowerCase().replaceAll("_", "") + "Service.java"); } catch (Exception e) { e.printStackTrace(); } } public void generateServiceImpl(String tableName) { try { Map params = new HashMap(); List columnlist = JDBCUtil.getTableColumns(con, null, null, tableName); params.put("columnlist", columnlist); params.put("tableName", tableName); params.put("pk", JDBCUtil.getPrimaryKeyColumns(con, null, null,tableName).get(0)); create("serviceimpl.ftl", params, BASE_PATH+"/src/" + SystemConstant.getProperty("code.serviceimpl").replace(".","/"),tableName.substring(0,1).toUpperCase()+tableName.substring(1).toLowerCase().replaceAll("_", "") + "Service.java"); } catch (Exception e) { e.printStackTrace(); } } public void generate(String tableName){ generateAction(tableName); generateApplicationContext(); generateDao(tableName); generateDaoImpl(tableName); generateList(tableName); generateModel(tableName); generateXwork(tableName); generatorJSP(tableName); generateValidation(tableName); generateValidation_properties(tableName); generateService(tableName); generateServiceImpl(tableName); } public static void main(String[] args) { CodeGenerator generator = new CodeGenerator(); // generator.generateDao("ADV_POSITION"); //generator.generateAction("ADV_POSITION"); generator.generatorJSP("ADV_POSITION"); } }
3。下面是jdbc底层操作类
/* * JDBCUtil.java * * Created on November 9, 2002, 4:27 PM */ package com.hyj.util; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import net.sf.hibernate.Hibernate; import net.sf.hibernate.type.NullableType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author Administrator */ public class JDBCUtil { private static final Log logger = LogFactory.getLog(JDBCUtil.class); public static class Column { public String name; public int sqlType; public int sqlColumnLength; public int sqlDecimalLength; public boolean sqlNotNull; public boolean sqlReadOnly; public NullableType hibernateType; public Class javaType; public String sqlTypeName; public String defalutValue; public boolean equals(Object o) { boolean rv = false; if (o != null && o instanceof JDBCUtil.Column) { rv = (name.equals(((JDBCUtil.Column)o).name)); } return rv; } public int hashCode() { return (name != null) ? name.hashCode() : 0; } public String getName() { return name; } public void setName(String name) { this.name = name; } public NullableType getHibernateType() { return hibernateType; } public void setHibernateType(NullableType hibernateType) { this.hibernateType = hibernateType; } public Class getJavaType() { return javaType; } public void setJavaType(Class javaType) { this.javaType = javaType; } public int getSqlColumnLength() { return sqlColumnLength; } public void setSqlColumnLength(int sqlColumnLength) { this.sqlColumnLength = sqlColumnLength; } public int getSqlDecimalLength() { return sqlDecimalLength; } public void setSqlDecimalLength(int sqlDecimalLength) { this.sqlDecimalLength = sqlDecimalLength; } public boolean isSqlNotNull() { return sqlNotNull; } public void setSqlNotNull(boolean sqlNotNull) { this.sqlNotNull = sqlNotNull; } public boolean isSqlReadOnly() { return sqlReadOnly; } public void setSqlReadOnly(boolean sqlReadOnly) { this.sqlReadOnly = sqlReadOnly; } public int getSqlType() { return sqlType; } public void setSqlType(int sqlType) { this.sqlType = sqlType; } public String getSqlTypeName() { return sqlTypeName; } public void setSqlTypeName(String sqlTypeName) { this.sqlTypeName = sqlTypeName; } public String getDefalutValue() { return defalutValue; } public void setDefalutValue(String defalutValue) { this.defalutValue = defalutValue; } }; public static List getCatalogs(Connection c) throws SQLException { DatabaseMetaData dmd = c.getMetaData(); ResultSet rs = null; try { rs = dmd.getCatalogs(); List l = new LinkedList(); while (rs.next()) { l.add(rs.getString(1)); } return l; } finally { if (rs != null) rs.close(); } } public static Map getSchemas(Connection c) throws SQLException { DatabaseMetaData dmd = c.getMetaData(); ResultSet rs = null; try { rs = dmd.getSchemas(); Map map = new HashMap(); List l; while (rs.next()) { String schema = rs.getString(1); String catalog = null; if (rs.getMetaData().getColumnCount() > 1) { catalog = rs.getString(2); }; l = (List)map.get(catalog); if (l == null) { l = new LinkedList(); map.put(catalog, l); } l.add(schema); } return map; } finally { if (rs != null) rs.close(); } } public static List getTables(Connection c, String catalog, String schema, String tablePattern) throws SQLException { logger.debug("catalog='" + catalog + "'"); logger.debug("schema='" + schema + "'"); logger.debug("table='" + tablePattern + "'"); DatabaseMetaData dmd = c.getMetaData(); ResultSet rs = null; try { rs = dmd.getTables(catalog, schema, tablePattern, new String[] {"TABLE", "VIEW", "SYNONYM", "ALIAS"} ); List l= new LinkedList(); while (rs.next()) { l.add(rs.getString(3)); } return l; } finally { if (rs != null) rs.close(); } } public static Set getForeignKeyColumns(Connection c, String catalog, String schema, String table) throws SQLException { logger.debug("catalog='" + catalog + "'"); logger.debug("schema='" + schema + "'"); logger.debug("table='" + table + "'"); DatabaseMetaData dmd = c.getMetaData(); ResultSet rs = null; try { rs = dmd.getImportedKeys(catalog, schema, table); HashSet columns = new HashSet(); while (rs.next()) { columns.add(rs.getString(8)); } return columns; } finally { if (rs != null) rs.close(); } } public static List getPrimaryKeyColumns(Connection c, String catalog, String schema, String table) throws SQLException { logger.debug("catalog='" + catalog + "'"); logger.debug("schema='" + schema + "'"); logger.debug("table='" + table + "'"); DatabaseMetaData dmd = c.getMetaData(); ResultSet rs = null; try { rs = dmd.getPrimaryKeys(catalog, schema, table); List pkColumns = new LinkedList();; while (rs.next()) { List tmp = getTableColumns(c, catalog, schema, table, rs.getString(4)); Column pkColumn = (Column)tmp.get(0); pkColumns.add(pkColumn); } return pkColumns; } finally { if (rs != null) rs.close(); } } public static List getTableColumns(Connection c, String catalog, String schema, String table) throws SQLException { return getTableColumns(c, catalog, schema, table, null); } public static List getTableColumns(Connection c, String catalog, String schema, String table, String columnPattern) throws SQLException { logger.debug("catalog='" + catalog + "'"); logger.debug("schema='" + schema + "'"); logger.debug("table='" + table + "'"); logger.debug("column='" + columnPattern+ "'"); DatabaseMetaData dmd = c.getMetaData(); ResultSet rs = null; try { rs = dmd.getColumns(catalog, schema, table, columnPattern); List columns = new LinkedList(); while (rs.next()) { JDBCUtil.Column aCol = new JDBCUtil.Column(); aCol.sqlTypeName = rs.getString(6); aCol.defalutValue = rs.getString(13); aCol.name = rs.getString(4); aCol.sqlType = rs.getShort(5); aCol.sqlColumnLength=rs.getInt(7); aCol.sqlDecimalLength=rs.getInt(9); aCol.sqlNotNull = ("NO".equals(rs.getString(18))); aCol.hibernateType = getHibernateType( aCol.sqlType, aCol.sqlColumnLength, aCol.sqlDecimalLength ); aCol.javaType = getJavaType( aCol.sqlType, aCol.sqlColumnLength, aCol.sqlDecimalLength ); columns.add(aCol); } return columns; } finally { if (rs != null) rs.close(); } } public static NullableType getHibernateType(int sqlType, int columnSize, int decimalDigits) { logger.debug("sqlType=" + sqlType); logger.debug("columnSize=" + columnSize); logger.debug("decimalDigits=" + decimalDigits); NullableType rv=Hibernate.SERIALIZABLE; if (sqlType == Types.CHAR || sqlType == Types.VARCHAR) { rv = Hibernate.STRING; } else if (sqlType == Types.FLOAT || sqlType == Types.REAL) { rv = Hibernate.FLOAT; } else if (sqlType == Types.INTEGER) { rv = Hibernate.INTEGER; } else if (sqlType == Types.DOUBLE) { rv = Hibernate.DOUBLE; } else if (sqlType == Types.DATE) { rv = Hibernate.DATE; } else if (sqlType == Types.TIMESTAMP) { rv = Hibernate.TIMESTAMP; } else if (sqlType == Types.TIME) { rv = Hibernate.TIME; } // commented to support JDK version < 1.4 /* else if (sqlType == Types.BOOLEAN) { rv = Hibernate.BOOLEAN; } */ else if (sqlType == Types.SMALLINT) { rv = Hibernate.SHORT; } else if (sqlType == Types.BIT) { rv = Hibernate.BYTE; } else if (sqlType == Types.BIGINT) { rv = Hibernate.LONG; } else if (sqlType == Types.NUMERIC || sqlType == Types.DECIMAL) { if (decimalDigits == 0) { if (columnSize == 1) { rv = Hibernate.BYTE; } else if (columnSize < 5) { rv = Hibernate.SHORT; } else if (columnSize < 10) { rv = Hibernate.INTEGER; } else { rv = Hibernate.LONG; } } else { if (columnSize < 9) { rv = Hibernate.FLOAT; } else { rv = Hibernate.DOUBLE; } } } return rv; } public static Class getJavaType(int sqlType, int columnSize, int decimalDigits) { logger.debug("sqlType=" + sqlType); logger.debug("columnSize=" + columnSize); logger.debug("decimalDigits=" + decimalDigits); Class rv=String.class; if (sqlType == Types.CHAR || sqlType == Types.VARCHAR) { rv = String.class; } else if (sqlType == Types.FLOAT || sqlType == Types.REAL) { rv = Float.class; } else if (sqlType == Types.INTEGER) { rv = Integer.class; } else if (sqlType == Types.DOUBLE) { rv = Double.class; } else if (sqlType == Types.DATE) { //rv = java.util.Date.class; rv = String.class; } else if (sqlType == Types.TIMESTAMP) { //rv = java.util.Date.class; rv = String.class; } else if (sqlType == Types.TIME) { //rv = java.util.Date.class; rv = String.class; } // commented to support JDK version < 1.4 /* else if (sqlType == Types.BOOLEAN) { rv = Boolean.class; } */ else if (sqlType == Types.SMALLINT) { rv = Short.class; } else if (sqlType == Types.BIT) { // rv = Byte.class; rv = Integer.class; } else if (sqlType == Types.BIGINT) { rv = Long.class; } else if (sqlType == Types.NUMERIC || sqlType == Types.DECIMAL) { if (decimalDigits == 0) { if (columnSize == 1) { // rv = Byte.class; rv= Integer.class; } else if (columnSize < 5) { rv = Short.class; } else if (columnSize < 10) { rv = Integer.class; } else { rv = Long.class; } } else { if (columnSize < 9) { rv = Float.class; } else { rv = Double.class; } } } return rv; } }