diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c41509d --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +bin +.project +.classpath +.settings +.idea/compiler.xml +.idea/copyright/ +.idea/misc.xml +.idea/modules.xml +.idea/taover-java-generater.iml +.idea/workspace.xml +src/default.properties diff --git a/lib/commons-lang-2.6.jar b/lib/commons-lang-2.6.jar new file mode 100644 index 0000000..98467d3 Binary files /dev/null and b/lib/commons-lang-2.6.jar differ diff --git a/lib/freemarker-2.3.15.jar b/lib/freemarker-2.3.15.jar new file mode 100644 index 0000000..8b93b17 Binary files /dev/null and b/lib/freemarker-2.3.15.jar differ diff --git a/lib/mysql-connector-java-5.1.26-bin.jar b/lib/mysql-connector-java-5.1.26-bin.jar new file mode 100644 index 0000000..bf1e933 Binary files /dev/null and b/lib/mysql-connector-java-5.1.26-bin.jar differ diff --git a/src/com/taover/base/template/.svn/entries b/src/com/taover/base/template/.svn/entries new file mode 100644 index 0000000..e998df8 --- /dev/null +++ b/src/com/taover/base/template/.svn/entries @@ -0,0 +1,133 @@ +10 + +dir +115305 +svn://119.254.17.138/repos/%E6%B2%B1%E6%B2%B1%E7%94%9F%E6%B4%BB%E7%BD%91%E8%B6%85/code/soa.tootoo.cn/trunk/generate-tootoo-dao-po/src/cn/tootoo/base/template +svn://119.254.17.138/repos + + + +2015-02-04T12:03:01.165689Z +87604 +zhuruisong + + +svn:special svn:externals svn:needs-lock + + + + + + + + + + + +5351f05e-98f4-42cc-8e6a-33022518c94f + +DAOTemplate.ftl +file +120059 + + + +2015-08-26T08:17:12.564000Z +56d88466e50d589a4459ed064d4ac052 +2015-09-10T02:21:44.128446Z +120059 +wangzhangyu + + + + + + + + + + + + + + + + + + + + + +66099 + +POTemplate.ftl +file + + + + +2015-08-10T05:52:55.994000Z +1738d433df84ecb7349bfaf1f38109d4 +2014-07-16T08:31:16.396207Z +66550 +wangpeng + + + + + + + + + + + + + + + + + + + + + +3290 + +createTableTemplate.ftl +file + + + + +2015-08-10T05:52:55.971000Z +77e6408085e1fc552a74e199f2c0b762 +2014-10-17T09:18:28.728707Z +76466 +zhuruisong + + + + + + + + + + + + + + + + + + + + + +1127 + +model +dir + diff --git a/src/com/taover/base/template/.svn/text-base/DAOTemplate.ftl.svn-base b/src/com/taover/base/template/.svn/text-base/DAOTemplate.ftl.svn-base new file mode 100644 index 0000000..92850fb --- /dev/null +++ b/src/com/taover/base/template/.svn/text-base/DAOTemplate.ftl.svn-base @@ -0,0 +1,1545 @@ +//${tableName} +<#--包名 --> +package ${packages} + +<#-- 所有的引入--> +<#list imports as ilist> +<#if ilist?exists>${ilist}<#else><#rt> + +import java.math.BigDecimal; + +/** + <#if version?exists> + * @version ${version} + + */ + +<#--类, 还是接口 名称, 继承的类, 实现的接口 --> +public class ${beanName}Dao { +<#--变量 --> +<#if propertys?exists> +<#list propertys as prolist> + <#if prolist?exists> + ${prolist}<#rt> + + + + /** + * 初始化 + */ + public ${beanName}Dao() { + } + + /** + * 初始化 + */ + public ${beanName}Dao(String uuid) { + this.uuid = uuid; + } + + /** + * 初始化 + */ + public ${beanName}Dao(String uuid, Logger logger) { + this.uuid = uuid; +// if(logger != null){ +// this.logger = logger; +// } + } + + /** + * 提交 + */ + public void commit() { + JdbcUtil.commit(writeConnectionName); + } + + /** + * 回滚 + */ + public void rollback() { + JdbcUtil.rollback(writeConnectionName); + } + + /** + * 初始化cacheColums + */ + public static void initCache() { + cacheColums = new ArrayList(); + } + + /** + * 线程修改cacheColums + */ + public static void threadResetCache(ArrayList list) { + if (cacheColums == null) + initCache(); + cacheColums.clear(); + for (int i = 0; i < list.size(); i++) + cacheColums.add((String) list.get(i)); + } + + /** + * 重置cache + */ + public void resetCache(final List<${beanName}PO> list) { + if (null == list || list.size() <= 0) + return; + Thread thread = new Thread() { + public void run() { + List haveResetList = new ArrayList(); + for (${beanName}PO po : list) { + Memcached.delete("1_${tableName}_PK_" + po.get${pkBeanName}()); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"一级缓存删除 key[1_${tableName}_PK_" + po.get${pkBeanName}() + "]"); + Long keyTime = System.currentTimeMillis(); + for (int i = 0; i < cacheColums.size(); i++) { + String key = (String) cacheColums.get(i); + String cache_key = "2_${tableName}_" + key + "_" + StringUtil.getValueFromObjectByName(po, key); + if (!haveResetList.contains(cache_key)) { + Memcached.add(2, cache_key, keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存重置 key[" + cache_key + "]"); + haveResetList.add(cache_key); + } + } + } + Memcached.add(4, "4_${tableName}", System.currentTimeMillis()); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存重置 key[4_${tableName}]"); + } + }; + thread.start(); + } + + /** + * 从缓存中获取缓存列 + */ + public Object[] getCacheColFromCache(List condition) { + Object[] obj = { null, null }; + for (Object[] arg : condition) { + if (cacheColums.contains((String) arg[0])) { + if(!"=".equals((String)arg[1])){ //操作符为"="允许使用缓存列 + continue; + } + obj[0] = arg[0] + "_" + arg[2]; + obj[1] = Memcached.get("2_${tableName}_" + obj[0]); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存获取 key["+obj[0]+"],value["+obj[1]+"]"); + return obj; + } + } + return null; + } + + /** + * 根据Request Map 生成PO对象 + */ + public ${beanName}PO get${beanName}POFromRequest(Map map) throws Exception { + ${beanName}PO po = new ${beanName}PO(); + <#if reqParameterToPOMap?exists> + <#list reqParameterToPOMap?keys as poKey> + po.set${reqParameterToPOMap[poKey]}; + + + return po; + } + + /** + * 按主键查询 + */ + public ${beanName}PO find${beanName}POByID(${pkType} id) { + return find${beanName}POByID(id, false, true, true, false); + } + + /** + * 按主键查询 + * isLock 是否锁定, 默认不锁 + * isUseCache 是否用缓存, 默认用 + * isAddCache 查询结果是否添加到缓存, 默认添加 + */ + public ${beanName}PO find${beanName}POByID(${pkType} id, boolean isLock, boolean isUseCache, boolean isAddCache, boolean fromWriteDB) { + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + if (isUseCache) {// 从缓存中查询 + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"从一级缓存中查询,查询条件"+id); + Object obj = Memcached.get("1_${tableName}_PK_" + id); + if (obj != null) { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.find${beanName}POByID(" + id + ", " + isLock + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "一级缓存命中 key[1_${tableName}_PK_" + id +"]\n"+uuid + + "一级缓存查询结果:" + ((${beanName}PO) obj).toString() +"\n"+uuid + + "一级缓存查询时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return (${beanName}PO) obj; + } + } + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + sql.append(" WHERE ${pkColumName} = ?"); + pql.append(" WHERE ${pkColumName} = " + id); + if (isLock) { + sql.append(" FOR UPDATE"); + pql.append(" FOR UPDATE"); + } + List<${beanName}PO> resultList = null; + try { + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.find${beanName}POByID(" + id + ", " + isLock + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "连接名:" + (isLock ? writeConnectionName : (fromWriteDB ? writeConnectionName : readConnectionName)) + "\n"+uuid + + "准备执行SQL:" + pql.toString()); + } + resultList = JdbcUtil.executeQuery(uuid, (isLock ? writeConnectionName : (fromWriteDB ? writeConnectionName : readConnectionName)), sql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class), id); + if (resultList == null || resultList.size() == 0) { + Memcached.delete("1_${tableName}_PK_" + id); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"一级缓存删除 key[1_${tableName}_PK_" + id + "]"); + return null; + } + if (isAddCache) {// 把结果添加到缓存 + Memcached.add(1, "1_${tableName}_PK_" + id, resultList.get(0)); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"一级缓存添加 key[1_${tableName}_PK_" + id + "]"); + } + return resultList.get(0); + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, pql.toString(), id); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.find${beanName}POByID(" + id + ", " + isLock + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "连接名:" + (isLock ? writeConnectionName : (fromWriteDB ? writeConnectionName : readConnectionName)) + "\n"+uuid + + "执行SQL:" + pql.toString() + "\n"+uuid + + "返回数据条数:" + (resultList==null?0:resultList.size()) + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return null; + } + + /** + * 根据条件List查询 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public List<${beanName}PO> find${beanName}POListByCondition(List condition) { + return find${beanName}POListByCondition(condition, true, true, false); + } + + /** + * 根据条件List查询 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + * boolean isUseCache, 是否用缓存,默认用。 + * boolean isAddCache, 是否添加缓存,默认添加。 + */ + public List<${beanName}PO> find${beanName}POListByCondition(List condition, boolean isUseCache, boolean isAddCache, boolean fromWriteDB) { + if (StringUtil.isAutowired(condition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,无效请求!"), null, null); + return null; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + JdbcUtil.appendWhereCondition(sql, pql, list, condition); + List<${beanName}PO> resultList = null; + Object oColumAndTimeKey[] = null; + Object oTime = null; + if (isUseCache) {// 从缓存中查询 + + Log.info(logger,uuid,"从二级缓存中查询","查询条件",StringUtil.transferObjectList(condition)); + oColumAndTimeKey = getCacheColFromCache(condition); + oTime = (oColumAndTimeKey == null) ? null : oColumAndTimeKey[1]; + if (null != oTime) { + Object object = Memcached.get("3_" + MD5.md5(pql.toString() + oTime.toString())); + if (object != null) { + List<${beanName}PO> r = (List<${beanName}PO>) object; + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.find${beanName}POListByCondition(" + condition.toString() + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "二级三级缓存命中 key[3_" + MD5.md5(pql.toString() + oTime.toString()) + "]\n"+uuid + + "三级缓存查询返回条数:" + (r==null?0:r.size()) + "\n"+uuid + + "三级缓存查询时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return r; + } + } + } + try { + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.find${beanName}POListByCondition(" + condition.toString() + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "连接名:" + (fromWriteDB ? writeConnectionName : readConnectionName) + "\n"+uuid + + "准备执行SQL:" + pql.toString() ); + + } + resultList = JdbcUtil.executeQuery(uuid, fromWriteDB ? writeConnectionName : readConnectionName, sql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class), list.toArray()); + if (isAddCache) {// 把结果添加到缓存 + if (oColumAndTimeKey == null && !isUseCache) + oColumAndTimeKey = getCacheColFromCache(condition); + if (oColumAndTimeKey != null) { + if (oColumAndTimeKey[1] == null) { + oColumAndTimeKey[1] = System.currentTimeMillis(); + Memcached.add(2, "2_${tableName}_" + oColumAndTimeKey[0], oColumAndTimeKey[1]); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存添加 key[2_${tableName}_" + oColumAndTimeKey[0] + "]" ); + } + Memcached.add(3, "3_" + MD5.md5(pql.toString() + oColumAndTimeKey[1]), resultList); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"三级缓存添加 key[3_" + MD5.md5(pql.toString() + oColumAndTimeKey[1]) + "]" ); + } + } + return resultList; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, pql.toString(), null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.find${beanName}POListByCondition(" + condition.toString() + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "连接名:" + (fromWriteDB ? writeConnectionName : readConnectionName) + "\n"+uuid + + "执行SQL:" + pql.toString() + "\n"+uuid + + "返回条数:" + (resultList==null?0:resultList.size()) + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + + } + } + return null; + } + + /** + * 根据条件sql查询 + * sqlCondition 为where 后面的条件。 + */ + public List<${beanName}PO> find${beanName}POListBySql(String sqlCondition) { + return find${beanName}POListBySql(sqlCondition, true, true, false); + } + + /** + * 根据条件sql查询 + * sqlCondition 为where 后面的条件。 + */ + public List<${beanName}PO> find${beanName}POListBySql(String sqlCondition, boolean isUseCache, boolean isAddCache, boolean fromWriteDB) { + if (StringUtil.isAutowired(sqlCondition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,无效请求!"), null, null); + return null; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName} WHERE " + sqlCondition); + List<${beanName}PO> resultList = null; + Object oTime = null; + if (isUseCache) {// 从缓存中查询 + oTime = Memcached.get("4_${tableName}"); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存中获取 key[4_${tableName}],value[" + oTime + "]"); + if (null != oTime) { + Object object = Memcached.get("3_" + MD5.md5(sql.toString() + oTime.toString())); + if (null != object) { + List<${beanName}PO> r = (List<${beanName}PO>) object; + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.find${beanName}POListBySql(" + sqlCondition + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "四级三级缓存命中 key[3_" + MD5.md5(sql.toString() + oTime.toString()) + "]\n"+uuid + + "三级缓存返回条数:" + (r==null?0:r.size()) + "\n"+uuid + + "三级缓存查询时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return r; + } + } + } + try { + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.find${beanName}POListBySql(" + sqlCondition + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "连接名:" + (fromWriteDB ? writeConnectionName : readConnectionName) + "\n" + + "准备执行SQL:" + sql.toString() ); + } + resultList = JdbcUtil.executeQuery(uuid, fromWriteDB ? writeConnectionName : readConnectionName, sql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class)); + if (isAddCache) {// 重置缓存 + long keyTime = 0; + if (oTime != null) { + keyTime = (Long) oTime; + } else { + keyTime = System.currentTimeMillis(); + Memcached.add(4, "4_${tableName}", keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存重置 key[4_${tableName}]"); + } + Memcached.add(3, "3_" + MD5.md5(sql.toString() + keyTime), resultList); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"三级缓存添加 key[3_" + MD5.md5(sql.toString() + keyTime) + "]"); + } + return resultList; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, sql.toString(), null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.find${beanName}POListBySql(" + sqlCondition + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "连接名:" + (fromWriteDB ? writeConnectionName : readConnectionName) + "\n"+uuid + + "执行SQL:" + sql.toString() + "\n" + + "返回条数:" + (resultList==null?0:resultList.size()) + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return null; + } + + /** + * 按条件分页查询 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public Map findPageByCondition(List condition, int page, int pageSize, String sortCondition) { + return findPageByCondition(condition, page, pageSize, true, true, sortCondition, false); + } + + /** + * 按条件分页查询 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + * boolean isUseCache, 是否用缓存,默认用。 + * boolean isAddCache, 是否添加缓存,默认添加。 + */ + public Map findPageByCondition(List condition, int page, int pageSize, boolean isUseCache, boolean isAddCache, String sortCondition, boolean fromWriteDB) { + if (StringUtil.isAutowired(condition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,无效请求!"), null, null); + return null; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + <#if dbType = "mysql"> + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + <#else> + StringBuffer sql = new StringBuffer("SELECT ${column_list_str}, ROWNUM RN FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + + StringBuffer sqlCount = new StringBuffer("SELECT COUNT(1) FROM ${tableName}"); + + List count_list = new ArrayList(); + List page_list = new ArrayList(); + JdbcUtil.appendWhereConditionForCount(sqlCount, condition); + JdbcUtil.appendWhereCondition(sql, pql, count_list, condition); + for (int i = 0; i < count_list.size(); i++) + page_list.add(count_list.get(i)); + + <#if dbType == "mysql"> + page_list.add((page - 1) * pageSize); + page_list.add(page * pageSize); + if(StringUtil.isEmpty(sortCondition)){ + String pageSql = sql.toString() + " limit ?, ?"; + String pagePql = pql.toString() + " limit " + (page -1) * pageSize + ", " + page * pageSize; + }else{ + String pageSql = sql.toString() + sortCondition + " limit ?, ?"; + String pagePql = pql.toString() + sortCondition + " limit " + (page -1) * pageSize + ", " + page * pageSize; + } + + <#else> + String pageSql = null; + String pagePql = null; + if (page_list.size() == 0) { + if(StringUtil.isEmpty(sortCondition)){ + pageSql = "SELECT * FROM (" + sql.toString() + " AND ROWNUM <= ?" + ") A WHERE A.RN >= ?"; + pagePql = "SELECT * FROM (" + pql.toString() + " AND ROWNUM <= " + page * pageSize + ") A WHERE A.RN >= " + ((page -1) * pageSize + 1); + }else{ + pageSql = "SELECT * FROM (SELECT B.*,ROWNUM RNN FROM (" + sql.toString() + " " + sortCondition + ") B WHERE ROWNUM <= ?"+" ) A WHERE A.RNN >= ?"; + pagePql = "SELECT * FROM (SELECT B.*,ROWNUM RNN FROM (" + pql.toString() + " " + sortCondition + ") B WHERE ROWNUM <= " + page * pageSize + ") A WHERE A.RNN >= " + ((page -1) * pageSize + 1); + } + + } else { + if(StringUtil.isEmpty(sortCondition)){ + pageSql = "SELECT * FROM (" + sql.toString() + " AND ROWNUM <= ?" + ") A WHERE A.RN >= ?"; + pagePql = "SELECT * FROM (" + pql.toString() + " AND ROWNUM <= " + page * pageSize + ") A WHERE A.RN >= " + ((page -1) * pageSize + 1); + }else{ + pageSql = "SELECT * FROM (SELECT B.*,ROWNUM RNN FROM (" + sql.toString() + " " + sortCondition + ") B WHERE ROWNUM <= ?"+" ) A WHERE A.RNN >= ?"; + pagePql = "SELECT * FROM (SELECT B.*,ROWNUM RNN FROM (" + pql.toString() + " " + sortCondition + ") B WHERE ROWNUM <= " + page * pageSize + ") A WHERE A.RNN >= " + ((page -1) * pageSize + 1); + } + } + page_list.add(page * pageSize); + page_list.add((page - 1) * pageSize + 1); + + + Object oColumAndTimeKey[] = null; + Object oTime = null; + if (isUseCache) {// 从缓存中查询 + Log.info(logger,uuid,"从二级缓存中查询","查询条件",StringUtil.transferObjectList(condition)); + oColumAndTimeKey = getCacheColFromCache(condition); + oTime = (oColumAndTimeKey == null) ? null : oColumAndTimeKey[1]; + if (null != oTime) { + Object object = Memcached.get("3_" + MD5.md5(pagePql.toString() + oTime.toString())); + if (null != object) { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.findPageByCondition(" + condition.toString() + ", " + page + ", " + pageSize + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "二级三级缓存命中 key[3_" + MD5.md5(pagePql.toString() + oTime.toString()) + "]\n"+uuid + + "三级缓存返回条数:" + (((Map) object).get("list") == null?0:((List<${beanName}PO>)((Map) object).get("list")).size()) + "\n"+uuid + + "三级缓存查询时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return (Map) object; + } + } + } + List<${beanName}PO> resultList = null; + try { + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.findPageByCondition(" + condition.toString() + ", " + page + ", " + pageSize + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "连接名:" + (fromWriteDB ? writeConnectionName : readConnectionName) + "\n"+uuid + + "准备执行SQL:" + pagePql.toString() ); + } + int totalPages = 0; + int totalRows = JdbcUtil.queryForInt(uuid, fromWriteDB ? writeConnectionName : readConnectionName, sqlCount.toString(), count_list.toArray()) ; + if (totalRows % pageSize == 0) { + totalPages = totalRows / pageSize; + } else { + totalPages = (totalRows / pageSize) + 1; + } + Map resultMap = new HashMap(); + resultMap.put("rows", totalRows); + resultMap.put("page", page); + resultMap.put("records", totalRows); + resultMap.put("total", totalPages); + resultList = JdbcUtil.executeQuery(uuid, fromWriteDB ? writeConnectionName : readConnectionName, pageSql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class), page_list.toArray()); + resultMap.put("list", resultList); + if (isAddCache) {// 把结果添加到缓存 + if (oColumAndTimeKey == null && !isUseCache) + oColumAndTimeKey = getCacheColFromCache(condition); + if (oColumAndTimeKey != null) { + if (oColumAndTimeKey[1] == null) { + oColumAndTimeKey[1] = System.currentTimeMillis(); + Memcached.add(2, "2_${tableName}_" + oColumAndTimeKey[0], oColumAndTimeKey[1]); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存重置 key[2_${tableName}_" + oColumAndTimeKey[0] + "]"); + } + Memcached.add(3, "3_" + MD5.md5(pagePql.toString() + oColumAndTimeKey[1]), resultMap); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"三级缓存添加 key[3_" + MD5.md5(pagePql.toString() + oColumAndTimeKey[1]) + "]"); + } + } + return resultMap; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, pagePql.toString(), page_list.toArray()); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.findPageByCondition(" + condition.toString() + ", " + page + ", " + pageSize + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "连接名:" + (fromWriteDB ? writeConnectionName : readConnectionName) + "\n"+uuid + + "执行SQL:" + pagePql.toString() + "\n"+uuid + + "返回条数:" + (resultList==null?0:resultList.size()) + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return null; + } + + /** + * 按sql分页查询, sqlCondition为where 后条件sql + */ + public Map findPageBySql(String sqlCondition, int page, int pageSize, String sortCondition) { + return findPageBySql(sqlCondition, page, pageSize, true, true, sortCondition, false); + } + + /** + * 按sql分页查询, sqlCondition为where 后条件sql + */ + public Map findPageBySql(String sqlCondition, int page, int pageSize, boolean isUseCache, boolean isAddCache, String sortCondition, boolean fromWriteDB) { + if (StringUtil.isAutowired(sqlCondition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,无效请求!"), null, null); + return null; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + + <#if dbType = "mysql"> + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName} WHERE " + sqlCondition + sortCondition); + StringBuffer sqlCount = new StringBuffer("SELECT count(1) from ${tableName} WHERE " + sqlCondition); + String pageSql = sql.toString() + " limit ?, ?"; + String pagePql = sql.toString() + " limit " + ((page -1) * pageSize) + ", " + (page * pageSize); + List page_list = new ArrayList(); + page_list.add((page - 1) * pageSize); + page_list.add(page * pageSize); + <#else> + StringBuffer sql = new StringBuffer("SELECT ${column_list_str}, ROWNUM RN FROM ${tableName} WHERE " + sqlCondition); + StringBuffer sqlCount = new StringBuffer("SELECT count(1) from ${tableName} WHERE " + sqlCondition); + String pageSql = null; + String pagePql = null; + if(StringUtil.isEmpty(sortCondition)){ + pageSql = "SELECT * FROM (" + sql.toString() + " AND ROWNUM <= ?" + ") A WHERE A.RN >= ?"; + pagePql = "SELECT * FROM (" + sql.toString() + " AND ROWNUM <= " + page * pageSize + ") A WHERE A.RN >= " + ((page -1) * pageSize + 1); + }else{ + pageSql = "SELECT * FROM (SELECT B.*,ROWNUM RNN FROM (" + sql.toString() + " " + sortCondition + ") B WHERE ROWNUM <= ?"+" ) A WHERE A.RNN >= ?"; + pagePql = "SELECT * FROM (SELECT B.*,ROWNUM RNN FROM (" + sql.toString() + " " + sortCondition + ") B WHERE ROWNUM <= " + page * pageSize + ") A WHERE A.RNN >= " + ((page -1) * pageSize + 1); + } + + List page_list = new ArrayList(); + page_list.add(page * pageSize); + page_list.add((page - 1) * pageSize + 1); + + + + Object oTime = null; + if (isUseCache) {// 从缓存中查询 + oTime = Memcached.get("4_${tableName}"); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存中获取 key[4_${tableName}],value[" + oTime + "]"); + if (null != oTime) { + Object object = Memcached.get("3_" + MD5.md5(pagePql.toString() + oTime.toString())); + if (null != object) { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.findPageBySql(" + sqlCondition + ", " + page + ", " + pageSize + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n" + + "四级三级缓存命中 key[3_" + MD5.md5(pagePql.toString() + oTime.toString()) + "]\n"+uuid + + "三级缓存返回条数:" + (((Map) object).get("list") == null?0:((List<${beanName}PO>)((Map) object).get("list")).size()) + "\n"+uuid + + "三级缓存查询时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return (Map) object; + } + } + } + List<${beanName}PO> resultList = null; + try { + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.findPageBySql(" + sqlCondition + ", " + page + ", " + pageSize + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n" + + "连接名:" + (fromWriteDB ? writeConnectionName : readConnectionName) + "\n"+uuid + + "准备执行SQL:" + pagePql.toString() ); + } + int totalPages = 0; + int totalRows = JdbcUtil.queryForInt(uuid, fromWriteDB ? writeConnectionName : readConnectionName, sqlCount.toString()); + if (totalRows % pageSize == 0) { + totalPages = totalRows / pageSize; + } else { + totalPages = (totalRows / pageSize) + 1; + } + Map resultMap = new HashMap(); + resultMap.put("rows", totalRows); + resultMap.put("page", page); + resultMap.put("records", totalRows); + resultMap.put("total", totalPages); + resultList = JdbcUtil.executeQuery(uuid, fromWriteDB ? writeConnectionName : readConnectionName, pageSql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class), page_list.toArray()); + resultMap.put("list", resultList); + if (isAddCache) {// 重置缓存 + long keyTime = 0; + if (oTime != null) { + keyTime = (Long) oTime; + } else { + keyTime = System.currentTimeMillis(); + Memcached.add(4, "4_${tableName}", keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存重置 key[4_${tableName}]"); + } + Memcached.add(3, "3_" + MD5.md5(pagePql.toString() + keyTime), resultMap); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"三级缓存添加 key[3_" + MD5.md5(pagePql.toString() + keyTime) + "]"); + } + return resultMap; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, pagePql.toString(), null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.findPageBySql(" + sqlCondition + ", " + page + ", " + pageSize + ", " + isUseCache + ", " + isAddCache + ", " + fromWriteDB + ")\n"+uuid + + "连接名:" + (fromWriteDB ? writeConnectionName : readConnectionName) + "\n"+uuid + + "执行SQL:" + pagePql.toString() + "\n"+uuid + + "返回条数:" + (resultList==null?0:resultList.size()) + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return null; + } + /** + *添加 + */ + public int directAdd${beanName}PO(${beanName}PO ${beanName}) { + if (null == ${beanName}) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,${beanName}不能为空!"), null, null); + return -1; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + <#-- + if (${beanName}.get${pkBeanName}() == null) { + ${beanName}.set${pkBeanName}(this.find${beanName}POSeqNextVal()); + } + --> + <#if columnList?exists> + <#list columnList as clist> + <#if clist.seqName?exists> + if (${beanName}.get${pkBeanName}() == null) { + ${beanName}.set${clist.columnUName}(this.findSeqNextVal("${clist.seqName}")); + } + + + + StringBuffer sql = new StringBuffer("INSERT INTO ${tableName}(" + "${column_list_str}" + ") VALUES ("); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + <#if columnList?exists> + <#list columnList as clist> + sql.append(" ?, "); + pql.append(${beanName}.get${clist.columnUName}() + ", "); + list.add(${beanName}.get${clist.columnUName}()); + + + + int count = 0; + try { + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.directAdd${beanName}PO (${beanName}PO ${beanName})\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "准备执行SQL:" + StringUtil.removeLast(pql.toString()) + ")" ); + } + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, StringUtil.removeLast(sql.toString()) + ")", list.toArray()); + + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, StringUtil.removeLast(pql.toString()) + ")", null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.directAdd${beanName}PO (${beanName}PO ${beanName})\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "执行SQL:" + StringUtil.removeLast(pql.toString()) + ")" + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + /** + * 添加 + */ + public int add${beanName}PO(${beanName}PO ${beanName}) { + if (null == ${beanName}) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,${beanName}不能为空!"), null, null); + return -1; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + <#-- + if (${beanName}.get${pkBeanName}() == null) { + ${beanName}.set${pkBeanName}(this.find${beanName}POSeqNextVal()); + } + --> + <#if columnList?exists> + <#list columnList as clist> + <#if clist.seqName?exists> + if (${beanName}.get${pkBeanName}() == null) { + ${beanName}.set${clist.columnUName}(this.findSeqNextVal("${clist.seqName}")); + } + + + + StringBuffer sql = new StringBuffer("INSERT INTO ${tableName}(" + "${column_list_str}" + ") VALUES ("); + StringBuffer sqlI = new StringBuffer("INSERT INTO ${tableName}("); + StringBuffer sqlC = new StringBuffer(") VALUES ("); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + <#if columnList?exists> + <#list columnList as clist> + if(${beanName}.get${clist.columnUName}() != null){ + sqlI.append("${clist.columnName},"); + sqlC.append(" ?, "); + pql.append(${beanName}.get${clist.columnUName}() + ", "); + list.add(${beanName}.get${clist.columnUName}()); + } + + + + + int count = 0; + try { + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.add${beanName}PO (${beanName}PO ${beanName})\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "准备执行SQL:" + StringUtil.removeLast(pql.toString()) + ")" ); + } + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, StringUtil.removeLast(StringUtil.removeLast(sqlI.toString())+sqlC.toString()) + ")", list.toArray()); + if (count > 0) { + long keyTime = System.currentTimeMillis(); + for (int i = 0; i < cacheColums.size(); i++) { + String key = cacheColums.get(i); + String cache_key = "2_${tableName}_" + key + "_" + StringUtil.getValueFromObjectByName(${beanName}, key); + Memcached.add(2, cache_key, keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存重置 key[" + cache_key + "]"); + } + Memcached.add(4, "4_${tableName}", keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存重置 key[4_${tableName}]"); + } + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, StringUtil.removeLast(pql.toString()) + ")", null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.add${beanName}PO (${beanName}PO ${beanName})\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "执行SQL:" + StringUtil.removeLast(pql.toString()) + ")" + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + /** + * 批量添加 + */ + public int add${beanName}POList(List<${beanName}PO> ${beanName}list) { + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + int count = 0; + for (${beanName}PO ${beanName} : ${beanName}list) { + count += add${beanName}PO(${beanName}); + } + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.add${beanName}POList(List<${beanName}PO> ${beanName}list)\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return count; + } + /** + * 按ID删除 + */ + public int remove${beanName}POByID(${pkType} id) { + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + StringBuffer sql = new StringBuffer("DELETE FROM ${tableName} WHERE"); + StringBuffer pql = new StringBuffer(sql.toString()); + pql.append(" ${pkColumName} = " + id); + sql.append(" ${pkColumName} = ?"); + int count = 0; + try { + ${beanName}PO oldPO = find${beanName}POByID(id, false, true, false, false); + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.remove${beanName}POByID(${pkType} id)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "准备执行SQL:" + pql.toString() ); + } + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, sql.toString(), id); + if (count > 0) { + + long keyTime = System.currentTimeMillis(); + Memcached.delete("1_${tableName}_PK_" + id); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"一级缓存删除 key[1_${tableName}_PK_" + id + "]"); + for (int i = 0; i < cacheColums.size(); i++) { + String key = cacheColums.get(i); + String cache_key = "2_${tableName}_" + key + "_" + StringUtil.getValueFromObjectByName(oldPO, key); + Memcached.add(2, cache_key, keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存重置 key[" + cache_key + "]"); + } + Memcached.add(4, "4_${tableName}", keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存重置 key[4_${tableName}]"); + } + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, pql.toString(), null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.remove${beanName}POByID(${pkType} id)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "执行SQL:" + pql.toString() + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + /** + *根据ID删除,不走缓存 + */ + public int directRemove${beanName}POByID(${pkType} id) { + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + StringBuffer sql = new StringBuffer("DELETE FROM ${tableName} WHERE"); + StringBuffer pql = new StringBuffer(sql.toString()); + pql.append(" ${pkColumName} = " + id); + sql.append(" ${pkColumName} = ?"); + int count = 0; + try { + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, sql.toString(), id); + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, pql.toString(), null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.directRemove${beanName}POByID(${pkType} id)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "执行SQL:" + pql.toString() + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + /** + * 删除按List条件 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public int remove${beanName}POByCondition(List condition) { + if (null == condition || condition.size() == 0) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,请求条件List condition不能为空!"), null, null); + return -1; + } + if (StringUtil.isAutowired(condition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,无效请求!"), null, null); + return -1; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + List list = new ArrayList(); + StringBuffer sql = new StringBuffer("DELETE FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + JdbcUtil.appendWhereCondition(sql, pql, list, condition); + int count = 0; + try { + List<${beanName}PO> oldList = find${beanName}POListByCondition(condition, true, false, false); + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.remove${beanName}POByCondition(List condition)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "准备执行SQL:" + pql.toString() ); + } + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, sql.toString(), list.toArray()); + if (count > 0) {// 重置缓存 + resetCache(oldList); + } + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, pql.toString(), null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.remove${beanName}POByCondition(List condition)\n" + + "连接名:" + writeConnectionName + "\n" + + "执行SQL:" + pql.toString() + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + + /** + * 删除按condition条件 + * 建议使用remove${beanName}POByCondition(List condition), 如果remove${beanName}POByCondition(List condition)满足不了where条件可以使用此方法。 + * condition为where后面的条件,condition不能为空。 + */ + public int remove${beanName}POBySql(String sqlCondition) { + if (StringUtil.isEmpty(sqlCondition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,请求条件String sqlCondition不能为空!"), null, null); + return -1; + } + if (StringUtil.isAutowired(sqlCondition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,无效请求!"), null, null); + return -1; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + StringBuffer sql = new StringBuffer("DELETE FROM ${tableName} WHERE "); + int count = 0; + try { + List<${beanName}PO> oldList = find${beanName}POListBySql(sqlCondition, true, false, false); + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.remove${beanName}POBySql(String sqlCondition)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "准备执行SQL:" + sql.toString() + sqlCondition ); + } + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, sql.toString() + sqlCondition); + if (count > 0) {// 重置缓存 + resetCache(oldList); + } + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, sql.toString() + sqlCondition, null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.remove${beanName}POBySql(String sqlCondition)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "执行SQL:" + sql.toString() + sqlCondition + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + + /** + * 根据list对象逐个删除。 + */ + public int remove${beanName}POList(List<${beanName}PO> ${beanName}list) { + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + int count = 0; + for (${beanName}PO ${beanName} : ${beanName}list) { + count += remove${beanName}POByID(${beanName}.get${pkBeanName}()); + } + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.remove${beanName}POList(List<${beanName}PO> ${beanName}list)\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return count; + } + + /** + * 根据对象ID修改。 + */ + public int update${beanName}PO(${beanName}PO ${beanName}) { + if (null == ${beanName} || null == ${beanName}.get${pkBeanName}()) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,请求对象和对象ID不能为空!"), null, null); + return -1; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + StringBuffer sql = new StringBuffer("UPDATE ${tableName} SET"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + <#if columnList?exists> + <#list columnList as clist> + <#if clist.seqName?exists> + <#else> + <#if clist.columnJAVAType = "Long" || clist.columnJAVAType = "Integer" || clist.columnJAVAType = "Short" || clist.columnJAVAType = "Float" || clist.columnJAVAType = "Double"> + boolean ${clist.columnUName}IsZero = false; + Object variation${clist.columnUName} = ${beanName}.getVariation${clist.columnUName}(); + if (variation${clist.columnUName} instanceof BigDecimal) { + ${clist.columnUName}IsZero = (((BigDecimal)variation${clist.columnUName}).compareTo(BigDecimal.ZERO) == 0); + } else { + Long l${clist.columnUName} = Long.parseLong(String.valueOf(variation${clist.columnUName})); + ${clist.columnUName}IsZero = (l${clist.columnUName} == 0); + } + if (!${clist.columnUName}IsZero) { + sql.append(" ${clist.columnName} = ${clist.columnName} + ?, "); + pql.append(" ${clist.columnName} = ${clist.columnName} + " + ${beanName}.getVariation${clist.columnUName}() + ","); + list.add(${beanName}.getVariation${clist.columnUName}()); + } else { + sql.append(" ${clist.columnName} = ?, "); + pql.append(" ${clist.columnName} = " + ${beanName}.get${clist.columnUName}() + ","); + list.add(${beanName}.get${clist.columnUName}()); + } + <#elseif clist.columnJAVAType = "java.math.BigDecimal"> + if (${beanName}.getVariation${clist.columnUName}().compareTo(BigDecimal.ZERO) != 0) { + sql.append(" ${clist.columnName} = ${clist.columnName} + ?, "); + pql.append(" ${clist.columnName} = ${clist.columnName} + " + ${beanName}.getVariation${clist.columnUName}() + ","); + list.add(${beanName}.getVariation${clist.columnUName}()); + } else { + sql.append(" ${clist.columnName} = ?, "); + pql.append(" ${clist.columnName} = " + ${beanName}.get${clist.columnUName}() + ","); + list.add(${beanName}.get${clist.columnUName}()); + } + <#else> + sql.append(" ${clist.columnName} = ?, "); + pql.append(" ${clist.columnName} = " + ${beanName}.get${clist.columnUName}() + ","); + list.add(${beanName}.get${clist.columnUName}()); + + + + + + String where = " WHERE ${pkColumName} = ?"; + String pwhere = " WHERE ${pkColumName} = " + ${beanName}.get${pkBeanName}(); + list.add(${beanName}.get${pkBeanName}()); + int count = 0; + try { + List<${beanName}PO> oldList = find${beanName}POListBySql("${pkColumName} = " + ${beanName}.get${pkBeanName}(), true, false, false); + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.update${beanName}PO(${beanName}PO ${beanName})\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "准备执行SQL:" + StringUtil.removeLast(pql.toString()) + pwhere ); + } + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, StringUtil.removeLast(sql.toString()) + where, list.toArray()); + if (count > 0) { + long keyTime = System.currentTimeMillis(); + + //重置旧数据缓存 + for (${beanName}PO po : oldList) { + for (int i = 0; i < cacheColums.size(); i++) { + String key = (String) cacheColums.get(i); + String cache_key = "2_${tableName}_" + key + "_" + StringUtil.getValueFromObjectByName(po, key); + Memcached.add(2, cache_key, keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存重置 key[" + cache_key + "]"); + } + } + + //重置新数据缓存 + Memcached.add(1, "1_${tableName}_PK_" + ${beanName}.get${pkBeanName}(), ${beanName}); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"一级缓存添加 key[1_${tableName}_PK_" + ${beanName}.get${pkBeanName}() + "]"); + for (int i = 0; i < cacheColums.size(); i++) { + String key = cacheColums.get(i); + String cache_key = "2_${tableName}_" + key + "_" + StringUtil.getValueFromObjectByName(${beanName}, key); + Memcached.add(2, cache_key, keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存重置 key[" + cache_key + "]"); + } + Memcached.add(4, "4_${tableName}", keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存重置 key[4_${tableName}]"); + } + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, StringUtil.removeLast(pql.toString()) + pwhere, null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.update${beanName}PO(${beanName}PO ${beanName})\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "执行SQL:" + StringUtil.removeLast(pql.toString()) + pwhere + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + + /** + * 根据ID修改指定的值 + */ + public int update${beanName}FieldById(List changeList, ${pkType} id) { + if (null == id) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,请求对象和对象ID不能为空!"), null, null); + return -1; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + StringBuffer sql = new StringBuffer("UPDATE ${tableName} SET"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + Map map = new HashMap(); + for (int i = 0, iLen = changeList.size(); i < iLen; i++) { + String name = (String) changeList.get(i)[0]; + Object value = changeList.get(i)[1]; + String variationOpt = "="; + if (changeList.get(i).length > 2) + variationOpt = (String)changeList.get(i)[2]; + if (variationOpt.equals("=")) { + sql.append(" " + name + " = ?,"); + list.add(value); + if (value == null) { + pql.append(" " + name + "=null,"); + } else { + pql.append(" " + name + "=\"" + value.toString() + "\","); + } + map.put(name, value); + } else { + sql.append(" " + name + " = " + name + " + ?,"); + list.add(value); + pql.append(" " + name + " = " + name + " + " + value.toString() + ","); + <#--会有问题 暂留 + map.put(name, value);--> + } + } + + String where = " WHERE ${pkColumName}=?"; + String pwhere = " WHERE ${pkColumName}=\"" + id + "\""; + list.add(id); + int count = 0; + try { + List<${beanName}PO> oldList = find${beanName}POListBySql("${pkColumName} = " + id, true, false, false); + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.update${beanName}PO(List changeList, ${pkType} id)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "准备执行SQL:" + StringUtil.removeLast(pql.toString()) + pwhere ); + } + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, StringUtil.removeLast(sql.toString()) + where, list.toArray()); + if (count > 0) { + resetCache(oldList);// 重置缓存 + + //重置新数据缓存 + long keyTime = System.currentTimeMillis(); + Memcached.delete("1_${tableName}_PK_" + id); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"一级缓存删除 key[1_${tableName}_PK_" + id + "]"); + for (int i = 0; i < cacheColums.size(); i++) { + String key = cacheColums.get(i); + if(map.containsKey(key)){ + String cache_key = "2_${tableName}_" + key + "_" + map.get(key); + Memcached.add(2, cache_key, keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存重置 key[" + cache_key + "]"); + } + } + Memcached.add(4, "4_${tableName}", keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存重置 key[4_${tableName}]"); + } + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, StringUtil.removeLast(pql.toString()) + pwhere, null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.update${beanName}PO(List changeList, ${pkType} id)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "执行SQL:" + StringUtil.removeLast(pql.toString()) + pwhere + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + + /** + * 批量修改。 + */ + public int update${beanName}POList(List<${beanName}PO> ${beanName}list) { + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + int count = 0; + for (${beanName}PO ${beanName} : ${beanName}list) { + count += update${beanName}PO(${beanName}); + } + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.update${beanName}POList(List<${beanName}PO> ${beanName}list)\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return count; + } + + /** + * List updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 + * List condition 修改的条件, 数组长度是3, 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public int update${beanName}POByCondition(List updateObj, List condition) { + if (null == updateObj || updateObj.size() == 0) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,请求条件List updateObj不能为空!"), null, null); + return -1; + } + if (null == condition || condition.size() == 0) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,请求条件List condition不能为空!"), null, null); + return -1; + } + if (StringUtil.isAutowired(condition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,无效请求!"), null, null); + return -1; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + StringBuffer sql = new StringBuffer("UPDATE ${tableName} SET"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + JdbcUtil.appendSql(sql, pql, list, updateObj); + StringBuffer where = new StringBuffer(""); + StringBuffer pwhere = new StringBuffer(""); + JdbcUtil.appendWhereCondition(where, pwhere, list, condition); + int count = 0; + try { + List<${beanName}PO> oldList = find${beanName}POListByCondition(condition, true, false, false); + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.update${beanName}POByCondition(List updateObj, List condition)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "准备执行SQL:" + StringUtil.removeLast(pql.toString())+pwhere.toString() ); + } + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, StringUtil.removeLast(sql.toString()) + where.toString(), list.toArray()); + if (count > 0) { + resetCache(oldList);// 重置缓存 + + //重置新数据缓存 + Map map = new HashMap(); + for(int i = 0; i < updateObj.size(); i++){ + map.put(updateObj.get(i)[0], updateObj.get(i)[1]); + } + long keyTime = System.currentTimeMillis(); + for (int i = 0; i < cacheColums.size(); i++) { + String key = cacheColums.get(i); + if(map.containsKey(key)){ + String cache_key = "2_${tableName}_" + key + "_" + map.get(key); + Memcached.add(2, cache_key, keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存重置 key[" + cache_key + "]"); + } + } + Memcached.add(4, "4_${tableName}", keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存重置 key[4_${tableName}]"); + } + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, StringUtil.removeLast(pql.toString())+pwhere.toString(), null, null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.update${beanName}POByCondition(List updateObj, List condition)\n" + + "连接名:" + writeConnectionName + "\n"+uuid + + "执行SQL:" + StringUtil.removeLast(pql.toString())+pwhere.toString() + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + + /** + * List updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 + * String sqlCondition 修改的条件。 + */ + public int update${beanName}POBySql(List updateObj, String sqlCondition) { + if (null == updateObj || updateObj.size() == 0) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,请求条件List updateObj不能为空!"), null, null); + return -1; + } + if (StringUtil.isEmpty(sqlCondition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,请求条件sqlCondition不能为空!"), null, null); + return -1; + } + if (StringUtil.isAutowired(sqlCondition)) { + Log.error("error:[UUID:"+uuid+"]", logger, new Exception("请求条件异常,无效请求!"), null, null); + return -1; + } + Date starttime = null; + if (isLogInfo()) { + starttime = new Date(); + } + StringBuffer sql = new StringBuffer("UPDATE ${tableName} SET"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + JdbcUtil.appendSql(sql, pql, list, updateObj); + int count = 0; + try { + List<${beanName}PO> oldList = find${beanName}POListBySql(sqlCondition, true, false, false); + if (isLogInfo()) { + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.update${beanName}POBySql(List updateObj, String sqlCondition)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "准备执行SQL:" + StringUtil.removeLast(pql.toString()) + " WHERE " + sqlCondition ); + } + count = JdbcUtil.executeUpdate(uuid, writeConnectionName, StringUtil.removeLast(sql.toString()) + " WHERE "+sqlCondition, list.toArray()); + if (count > 0) { + resetCache(oldList);// 重置缓存 + + //重置新数据缓存 + Map map = new HashMap(); + for(int i = 0; i < updateObj.size(); i++){ + map.put(updateObj.get(i)[0], updateObj.get(i)[1]); + } + long keyTime = System.currentTimeMillis(); + for (int i = 0; i < cacheColums.size(); i++) { + String key = cacheColums.get(i); + if(map.containsKey(key)){ + String cache_key = "2_${tableName}_" + key + "_" + map.get(key); + Memcached.add(2, cache_key, keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"二级缓存重置 key[" + cache_key + "]"); + } + } + Memcached.add(4, "4_${tableName}", keyTime); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger,"四级缓存重置 key[4_${tableName}]"); + } + return count; + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, StringUtil.removeLast(pql.toString()) + " WHERE " + sqlCondition, null, null); + } finally { + if (isLogInfo()) { + Date endtime = new Date(); + Log.info("cacheinfo:[UUID:"+uuid+"]", logger, + "${beanName}Dao.update${beanName}POBySql(List updateObj, String sqlCondition)\n"+uuid + + "连接名:" + writeConnectionName + "\n"+uuid + + "执行SQL:" + StringUtil.removeLast(pql.toString()) + " WHERE " + sqlCondition + "\n"+uuid + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + } + return -1; + } + <#-- + /** + * 获取自增长ID + */ + public Integer find${beanName}POSeqNextVal() { + String sql = "SELECT SEQ_${tableName}_PK.NEXTVAL FROM DUAL"; + try { + return JdbcUtil.queryForInt(uuid, writeConnectionName, sql); + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, sql.toString()); + } + return -1; + } + --> + + /** + + * 获取自增长列的值(仅支持数值类型) + */ + <#-- public ${pkType} --> + public Long findSeqNextVal(String seq_name) { + String sql = "SELECT " + seq_name + ".NEXTVAL FROM DUAL"; + + try { + return Long.parseLong(JdbcUtil.queryForInt(uuid, writeConnectionName, sql)+""); + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, sql.toString()); + } + return -1l; + } + + /** + * 获取多个自增长ID + */ + public List<${pkType}> find${beanName}POSeqNextVal(Integer step, String seqName) { + String sql = "SELECT " + seqName + ".NEXTVAL FROM (SELECT 1 FROM ALL_OBJECTS WHERE ROWNUM <= "+step+" ) "; + try { + List<${pkType}> re = JdbcUtil.executeQuery(uuid, readConnectionName, sql.toString(), new DAORowMapper<${pkType}>(${pkType}.class)); + return re; + + } catch (Exception e) { + Log.error("error:[UUID:"+uuid+"]", logger, e, sql.toString()); + } + return null; + } + +<#--get, set方法集合 --> +<#if funlist?exists> +<#list funlist as flist> +<#--方法注释 --> + <#if flist.function_param?exists> + /** + <#list flist.function_param as param> + <#if param?exists>*@param ${param}<#else><#rt> + + <#list flist.function_exception as exception> + <#if exception?exists>*@throws ${exception}<#else><#rt> + + <#if flist.function_description?exists>*@Description:${flist.function_description}<#else><#rt> + */ + + <#--是否是override的 --> + <#if flist.over?exists>@Override<#else><#rt> + <#--类或者接口的方法不同所有有两个方法体 --> + <#-- 方法的定义--> + public ${flist.function_return} ${flist.function_name}(<#if flist.function_params?exists>${flist.function_params}<#else>)<#if flist.function_exceptions?exists> throws ${flist.function_exceptions}<#else> { + <#--方法体--> + ${flist.function_body} + } + + +} \ No newline at end of file diff --git a/src/com/taover/base/template/.svn/text-base/POTemplate.ftl.svn-base b/src/com/taover/base/template/.svn/text-base/POTemplate.ftl.svn-base new file mode 100644 index 0000000..e1353be --- /dev/null +++ b/src/com/taover/base/template/.svn/text-base/POTemplate.ftl.svn-base @@ -0,0 +1,108 @@ +<#--包名 --> +package ${packages} +import java.util.HashMap; +import java.util.Map; +import org.json.JSONException; +import org.json.JSONObject; +import java.io.Serializable; +/** + <#if version?exists> + * @version ${version} + + */ + + public class ${name}PO implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + <#--变量 ,get,set方法--> +<#if tablemodel.columnlist?exists> + <#list tablemodel.columnlist as clist> + private ${clist.columnJAVAType} ${clist.columnName}; + + <#if clist.columnRemarks?exists> + /** + * ${clist.columnRemarks} + */ + <#else> + + public ${clist.columnJAVAType} get${clist.columnMethodName}(){ + return ${clist.columnName}; + } + + public void set${clist.columnMethodName}(${clist.columnJAVAType} ${clist.columnName}){ + this.${clist.columnName} = ${clist.columnName}; + } + + <#if clist.columnJAVAType = "Long" || clist.columnJAVAType = "java.math.BigDecimal" || clist.columnJAVAType = "Integer" || clist.columnJAVAType = "Short" || clist.columnJAVAType = "Float" || clist.columnJAVAType = "Double"> + <#if clist.columnJAVAType = "Long"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0L; + + <#if clist.columnJAVAType = "java.math.BigDecimal"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = new java.math.BigDecimal(0.0); + + <#if clist.columnJAVAType = "Integer"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0; + + <#if clist.columnJAVAType = "Short"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0; + + <#if clist.columnJAVAType = "Double"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0d; + + <#if clist.columnJAVAType = "Float"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0f; + + public ${clist.columnJAVAType} getVariation${clist.columnMethodName}(){ + return variation${clist.columnMethodName}; + } + + public void setVariation${clist.columnMethodName}(${clist.columnJAVAType} variation${clist.columnName}){ + this.variation${clist.columnMethodName} = variation${clist.columnName}; + } + + + + + + @Override + public String toString() { + return "${name}PO: ${toStringMethodBody}; + } + + + public JSONObject toJson() { + JSONObject json = null; + try { + json = new JSONObject(); +<#if tablemodel.columnlist?exists> + <#list tablemodel.columnlist as clist> + json.put("${clist.columnName}", get${clist.columnMethodName}()); + + + } catch (JSONException e) { + e.printStackTrace(); + } + return json; + } + + public Map toMap() { + Map map = new HashMap(); +<#if tablemodel.columnlist?exists> + <#list tablemodel.columnlist as clist> + map.put("${clist.columnName}", get${clist.columnMethodName}()); + + + return map; + } + public ${name}PO JsonToPo(JSONObject json)throws JSONException{ + ${name}PO po = new ${name}PO(); +<#if tablemodel.columnlist?exists> + <#list tablemodel.columnlist as clist> + po.set${clist.columnMethodName}((${clist.columnJAVAType})json.get("${clist.columnName}")); + + return po; + + } + } \ No newline at end of file diff --git a/src/com/taover/base/template/.svn/text-base/createTableTemplate.ftl.svn-base b/src/com/taover/base/template/.svn/text-base/createTableTemplate.ftl.svn-base new file mode 100644 index 0000000..eb8e89f --- /dev/null +++ b/src/com/taover/base/template/.svn/text-base/createTableTemplate.ftl.svn-base @@ -0,0 +1,31 @@ +-- Create table +create table ${tableName} +( +<#list columnlist as clist> + ${clist.columnName} ${clist.columnSQLType}<#if clist.columnSize?exists>${clist.columnSize}<#if clist.columnDefaults?exists && clist.columnDefaults != '' && clist.columnDefaults != 'null'> default ${clist.columnDefaults}<#if !clist.nullable> not null<#if clist_has_next>, + +); +<#if tableRemarks?exists> +-- Add comments to the table +comment on table ${tableName} is '${tableRemarks}'; + +-- Add comments to the columns +<#list columnlist as clist> + <#if clist.columnRemarks?exists && clist.columnRemarks != clist.columnName> +comment on column ${tableName}.${clist.columnName} is '${clist.columnRemarks}'; + + +<#if tablePk?exists> +-- Create index +CREATE UNIQUE INDEX PK_${tableName} ON ${tableName}(${tablePk}); +ALTER TABLE ${tableName} ADD + PRIMARY KEY (${tablePk}) + USING INDEX PK_${tableName}; + +-- Create sequence +create sequence SEQ_${tableName}<#if tableName?length lt 24>_PK +minvalue 1 +maxvalue 99999999999999999 +start with 1 +increment by 1 +cache 20; diff --git a/src/com/taover/base/template/ControllerExportTemplate.ftl b/src/com/taover/base/template/ControllerExportTemplate.ftl new file mode 100644 index 0000000..f9939a4 --- /dev/null +++ b/src/com/taover/base/template/ControllerExportTemplate.ftl @@ -0,0 +1,51 @@ +package ${mainPackageInfo}.${moduleName}.export; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.propertyeditors.CustomDateEditor; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.taover.base.ResultInfo; +import ${mainPackageInfo}.contants.ResultInfoCode; +import com.taover.tools.CustomTimestampEditor; + +@Controller +@RequestMapping("/export/${moduleName}") +public class ${moduleNameFirstBig}ExportController { + + Log log = LogFactory.getLog(this.getClass()); + + /** + * 绑定日期参数 + * @param request + * @param binder + */ + @InitBinder + protected void init(HttpServletRequest request, WebDataBinder binder){ + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + dateFormat.setLenient(false); + binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); + SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + datetimeFormat.setLenient(false); + binder.registerCustomEditor(java.sql.Timestamp.class,new CustomTimestampEditor(datetimeFormat, true)); + } + +} diff --git a/src/com/taover/base/template/ControllerTemplate.ftl b/src/com/taover/base/template/ControllerTemplate.ftl new file mode 100644 index 0000000..ebcbd5b --- /dev/null +++ b/src/com/taover/base/template/ControllerTemplate.ftl @@ -0,0 +1,133 @@ +package ${mainPackageInfo}.${moduleName}.controller; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.propertyeditors.CustomDateEditor; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.taover.base.ResultInfo; +import ${mainPackageInfo}.contants.ResultInfoCode; +import ${poPackageInfo}.${poClassName}; +import ${mainPackageInfo}.${moduleName}.service.${serviceImplClassName}; +import com.taover.tools.CustomTimestampEditor; + +@Controller +@RequestMapping("/${controllerUri}") +public class ${controllerClassName} { + @Resource + private ${serviceImplClassName} ${serviceImplFieldName}; + + Log log = LogFactory.getLog(this.getClass()); + + /** + * 绑定日期参数 + * @param request + * @param binder + */ + @InitBinder + protected void init(HttpServletRequest request, WebDataBinder binder){ + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + dateFormat.setLenient(false); + binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); + SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + datetimeFormat.setLenient(false); + binder.registerCustomEditor(java.sql.Timestamp.class,new CustomTimestampEditor(datetimeFormat, true)); + } + + @RequestMapping(value="/add", method=RequestMethod.POST) + @ResponseBody + public ResultInfo add( + ${poClassName} ${poFieldName}, + Model model, + HttpServletRequest request){ + return this.${serviceImplFieldName}.add(${poFieldName}); + } + + @RequestMapping(value="/delete") + @ResponseBody + public ResultInfo delete( + @RequestParam(value="ids", required=false) String ids, + Model model, + HttpServletRequest request){ + //创建返回对象 + ResultInfo result = new ResultInfo(); + + //参数检验 + if(ids == null || ids.length() == 0){ + result.setResultId("200"); + result.setResultMessage("删除失败,缺少主键信息"); + return result; + } + + return result = this.${serviceImplFieldName}.delete(ids); + } + + @RequestMapping(value="/edit", method=RequestMethod.POST) + @ResponseBody + public ResultInfo edit( + ${poClassName} ${poFieldName}, + Model model, + HttpServletRequest request){ + + return this.${serviceImplFieldName}.edit(${poFieldName}); + } + + + /** + * 分页条件查询 + * @param page + * @param pageSize + * @return + */ + @RequestMapping(value = "/query") + @ResponseBody + public Map query( + @RequestParam(value="sort", required=false) String sort, + @RequestParam(value="order", required=false) String order, + @RequestParam(value="page", required=false) Integer page, + @RequestParam(value="rows", required=false) Integer pageSize, + HttpServletRequest request) { + //参数检验 + if(page == null){ + page = 1; + } + if(pageSize == null){ + pageSize = 20; + } + if("".equals(sort)){ + sort = "id"; + order = "desc"; + } + + //调用Service层查询方法 + List arrayCondition = new ArrayList(); + + <#list fields as tempField> + ${tempField["conditionCode"]} + + + Map result = this.${serviceImplFieldName}.query(arrayCondition, sort, order, page, pageSize); + result.put("resultId", "200"); + result.put("resultMessage", "请求成功"); + return result; + } + +} diff --git a/src/com/taover/base/template/DAOTemplate.ftl b/src/com/taover/base/template/DAOTemplate.ftl new file mode 100644 index 0000000..1bb82d3 --- /dev/null +++ b/src/com/taover/base/template/DAOTemplate.ftl @@ -0,0 +1,804 @@ +//${tableName} +<#--包名 --> +package ${packages} + +<#-- 所有的引入--> +<#list imports as ilist> +<#if ilist?exists>${ilist}<#else><#rt> + +import java.math.BigDecimal; + +/** + <#if version?exists> + * @version ${version} + + */ +@Repository +<#--类, 还是接口 名称, 继承的类, 实现的接口 --> +public class ${beanName}Dao { +<#--变量 --> + @Resource + private JdbcTemplate jdbcegroceryRead; + @Resource + private JdbcTemplate jdbcegroceryWrite; + + Log logger = LogFactory.getLog(this.getClass()); + + + /** + * 根据Request Map 生成PO对象 + */ + public ${beanName}PO get${beanName}POFromRequest(Map map) throws Exception { + ${beanName}PO po = new ${beanName}PO(); + <#if reqParameterToPOMap?exists> + <#list reqParameterToPOMap?keys as poKey> + po.set${reqParameterToPOMap[poKey]}; + + + return po; + } + + /** + * 按主键查询 + */ + public ${beanName}PO findPOByID(${pkType} id) { + return findPOByID(id, true, false); + } + + /** + * 按主键查询 + * isLock 是否锁定, 默认不锁 + * fromWriteDB 是否从写库读写,默认从读库查询 + */ + public ${beanName}PO findPOByID(${pkType} id, boolean isLock, boolean fromWriteDB) { + Date starttime = new Date(); + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + sql.append(" WHERE ${pkColumName} = ?"); + pql.append(" WHERE ${pkColumName} = " + id); + if (isLock) { + sql.append(" FOR UPDATE"); + pql.append(" FOR UPDATE"); + } + List<${beanName}PO> resultList = null; + try { + resultList = (fromWriteDB ? jdbcegroceryWrite : jdbcegroceryRead).query(sql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class), id); + if (resultList == null || resultList.size() == 0) { + return null; + } + return resultList.get(0); + } catch (Exception e) { + LogUtils.error("error:findPOByID", logger, e, pql.toString(), id); + } finally { + Date endtime = new Date(); + if(false)LogUtils.info("info:", logger, + "${beanName}Dao.findPOByID(" + id + ", " + isLock + ", " + ", " + fromWriteDB + ")\n" + + "返回数据条数:" + (resultList==null?0:resultList.size()) + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return null; + } + + /** + * 根据条件List查询 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public ${beanName}PO findPOByCondition(List condition) { + List<${beanName}PO> tempList = findListByCondition(condition,null, false); + if(tempList == null || tempList.size() == 0){ + return null; + }else{ + return tempList.get(0); + } + } + + /** + * 根据条件sql查询 + * sqlCondition 为where 后面的条件。 + */ + public ${beanName}PO findPOBySql(String sqlCondition) { + List<${beanName}PO> tempList = findListBySql(sqlCondition, false); + if(tempList == null || tempList.size() == 0){ + return null; + }else{ + return tempList.get(0); + } + } + + /** + * 根据条件List查询 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public List<${beanName}PO> findListByCondition(List condition) { + return findListByCondition(condition,null, false); + } + + /** + * 根据条件List查询 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public List<${beanName}PO> findListByCondition(List condition,String sortCondition, boolean fromWriteDB) { + if (StringUtil.isAutowired(condition)) { + LogUtils.error("error:", logger, new Exception("请求条件异常,无效请求!"), null, null); + return null; + } + Date starttime = new Date(); + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + JdbcUtil.appendWhereCondition(sql, pql, list, condition); + if(!StringUtils.isEmpty(sortCondition)){ + sql.append(" " + sortCondition + " "); + pql.append(" " + sortCondition + " "); + } + List<${beanName}PO> resultList = null; + try { + resultList = (fromWriteDB ? jdbcegroceryWrite : jdbcegroceryRead).query(sql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class), list.toArray()); + return resultList; + } catch (Exception e) { + LogUtils.error("error:", logger, e, pql.toString(), null); + } finally { + Date endtime = new Date(); + if(false)LogUtils.info("info", logger, + "${beanName}Dao.findListByCondition(" + condition.toString() + ", " + fromWriteDB + ")\n" + + "fromWriteDB:" + fromWriteDB + + "执行SQL:" + pql.toString() + "\n" + + "返回条数:" + (resultList==null?0:resultList.size()) + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + + } + return null; + } + + /** + * 根据条件sql查询 + * sqlCondition 为where 后面的条件。 + */ + public List<${beanName}PO> findListBySql(String sqlCondition) { + return findListBySql(sqlCondition, false); + } + + /** + * 根据条件sql查询 + * sqlCondition 为where 后面的条件。 + */ + public List<${beanName}PO> findListBySql(String sqlCondition,boolean fromWriteDB) { + if (StringUtil.isAutowired(sqlCondition)) { + LogUtils.error("error", logger, new Exception("请求条件异常,无效请求!"), null, null); + return null; + } + Date starttime = new Date(); + + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName} WHERE " + sqlCondition); + List<${beanName}PO> resultList = null; + try { + resultList = (fromWriteDB ? jdbcegroceryWrite : jdbcegroceryRead).query(sql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class)); + return resultList; + } catch (Exception e) { + LogUtils.error("error:", logger, e, sql.toString(), null); + } finally { + Date endtime = new Date(); + if(false)LogUtils.info("info", logger, + "${beanName}Dao.findListBySql(" + sqlCondition + ", " + fromWriteDB + ")\n" + + "fromWriteDB:" + fromWriteDB + "\n" + + "执行SQL:" + sql.toString() + "\n" + + "返回条数:" + (resultList==null?0:resultList.size()) + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return null; + } + + /** + * 按条件分页查询 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public Map findPageByCondition(List condition,int page, int pageSize) { + return findPageByCondition(condition, null , page, pageSize, false); + } + + /** + * 按条件分页查询 + * Object[]数组长度是3 + * Object[]第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + * boolean isUseCache, 是否用缓存,默认用。 + * boolean isAddCache, 是否添加缓存,默认添加。 + */ + public Map findPageByCondition(List condition,String sortCondition, int page, int pageSize, boolean fromWriteDB) { + if (StringUtil.isAutowired(condition)) { + LogUtils.error("error:", logger, new Exception("请求条件异常,无效请求!"), null, null); + return null; + } + Date starttime = new Date(); + <#if dbType = "mysql"> + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + <#else> + StringBuffer sql = new StringBuffer("SELECT ${column_list_str}, ROWNUM RN FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + + StringBuffer sqlCount = new StringBuffer("SELECT COUNT(1) FROM ${tableName}"); + + List count_list = new ArrayList(); + List page_list = new ArrayList(); + JdbcUtil.appendWhereConditionForCount(sqlCount, condition); + JdbcUtil.appendWhereCondition(sql, pql, count_list, condition); + for (int i = 0; i < count_list.size(); i++) + page_list.add(count_list.get(i)); + + <#if dbType == "mysql"> + page_list.add((page - 1) * pageSize); + page_list.add(pageSize); + + if(!StringUtils.isEmpty(sortCondition)){ + sql.append(" " + sortCondition + " "); + pql.append(" " + sortCondition + " "); + } + + String pageSql = sql.toString() + " limit ?, ?"; + String pagePql = pql.toString() + " limit " + (page -1) * pageSize + ", " + pageSize; + + <#else> + String pageSql = null; + String pagePql = null; + if (page_list.size() == 0) { + + pageSql = "SELECT * FROM (" + sql.toString() + " AND ROWNUM <= ?" + ") A WHERE A.RN >= ?"; + pagePql = "SELECT * FROM (" + pql.toString() + " AND ROWNUM <= " + page * pageSize + ") A WHERE A.RN >= " + ((page -1) * pageSize + 1); + } else { + pageSql = "SELECT * FROM (" + sql.toString() + " AND ROWNUM <= ?" + ") A WHERE A.RN >= ?"; + pagePql = "SELECT * FROM (" + pql.toString() + " AND ROWNUM <= " + page * pageSize + ") A WHERE A.RN >= " + ((page -1) * pageSize + 1); + } + page_list.add(page * pageSize); + page_list.add((page - 1) * pageSize + 1); + + List<${beanName}PO> resultList = null; + try { + int totalPages = 0; + int totalRows = (fromWriteDB ? jdbcegroceryWrite : jdbcegroceryRead).queryForInt(sqlCount.toString(), count_list.toArray()) ; + if (totalRows % pageSize == 0) { + totalPages = totalRows / pageSize; + } else { + totalPages = (totalRows / pageSize) + 1; + } + Map resultMap = new HashMap(); + resultMap.put("page", page); + resultMap.put("total", totalRows); + resultList = (fromWriteDB ? jdbcegroceryWrite : jdbcegroceryRead).query( pageSql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class), page_list.toArray()); + resultMap.put("rows", resultList); + return resultMap; + } catch (Exception e) { + LogUtils.error("error:", logger, e, pagePql.toString(), page_list.toArray()); + } finally { + Date endtime = new Date(); + if(false)LogUtils.info("info:", logger, + "${beanName}Dao.findPageByCondition(" + condition.toString() + ", " + page + ", " + pageSize + ", " + fromWriteDB + ")\n" + + "执行SQL:" + pagePql.toString() + "\n" + + "返回条数:" + (resultList==null?0:resultList.size()) + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return null; + } + + /** + * 按sql分页查询, sqlCondition为where 后条件sql + */ + public Map findPageBySql(String sqlCondition, int page, int pageSize) { + return findPageBySql(sqlCondition, page, pageSize, false); + } + + /** + * 按sql分页查询, sqlCondition为where 后条件sql + */ + public Map findPageBySql(String sqlCondition, int page, int pageSize,boolean fromWriteDB) { + if (StringUtil.isAutowired(sqlCondition)) { + LogUtils.error("error:", logger, new Exception("请求条件异常,无效请求!"), null, null); + return null; + } + Date starttime = new Date(); + + <#if dbType = "mysql"> + StringBuffer sql = new StringBuffer("SELECT ${column_list_str} FROM ${tableName} WHERE " + sqlCondition ); + StringBuffer sqlCount = new StringBuffer("SELECT count(1) from ${tableName} WHERE " + sqlCondition); + String pageSql = sql.toString() + " limit ?, ?"; + String pagePql = sql.toString() + " limit " + ((page -1) * pageSize) + ", " + (page * pageSize); + List page_list = new ArrayList(); + page_list.add((page - 1) * pageSize); + page_list.add(page * pageSize); + <#else> + StringBuffer sql = new StringBuffer("SELECT ${column_list_str}, ROWNUM RN FROM ${tableName} WHERE " + sqlCondition); + StringBuffer sqlCount = new StringBuffer("SELECT count(1) from ${tableName} WHERE " + sqlCondition); + String pageSql = null; + String pagePql = null; + + pageSql = "SELECT * FROM (" + sql.toString() + " AND ROWNUM <= ?" + ") A WHERE A.RN >= ?"; + pagePql = "SELECT * FROM (" + sql.toString() + " AND ROWNUM <= " + page * pageSize + ") A WHERE A.RN >= " + ((page -1) * pageSize + 1); + + + List page_list = new ArrayList(); + page_list.add(page * pageSize); + page_list.add((page - 1) * pageSize + 1); + + + + List<${beanName}PO> resultList = null; + try { + + int totalPages = 0; + int totalRows = (fromWriteDB ? jdbcegroceryWrite : jdbcegroceryRead).queryForInt(sqlCount.toString()); + if (totalRows % pageSize == 0) { + totalPages = totalRows / pageSize; + } else { + totalPages = (totalRows / pageSize) + 1; + } + Map resultMap = new HashMap(); + resultMap.put("page", page); + resultMap.put("total", totalRows); + resultList = (fromWriteDB ? jdbcegroceryWrite : jdbcegroceryRead).query(pageSql.toString(), new DAORowMapper<${beanName}PO>(${beanName}PO.class), page_list.toArray()); + resultMap.put("rows", resultList); + return resultMap; + } catch (Exception e) { + LogUtils.error("error:", logger, e, pagePql.toString(), null); + } finally { + Date endtime = new Date(); + if(false)LogUtils.info("info:", logger, + "${beanName}Dao.findPageBySql(" + sqlCondition + ", " + page + ", " + pageSize + ", " + fromWriteDB + ")\n" + + "fromWriteDB:" +fromWriteDB + "\n" + + "执行SQL:" + pagePql.toString() + "\n" + + "返回条数:" + (resultList==null?0:resultList.size()) + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return null; + } + + /** + * 添加 + */ + public int add${beanName}PO(${beanName}PO ${beanName}) { + if (null == ${beanName}) { + LogUtils.error("error:", logger, new Exception("请求条件异常,${beanName}不能为空!"), null, null); + return -1; + } + Date starttime = new Date(); + <#-- + if (${beanName}.get${pkBeanName}() == null) { + ${beanName}.set${pkBeanName}(this.find${beanName}POSeqNextVal()); + } + --> + <#if columnList?exists> + <#list columnList as clist> + <#if clist.seqName?exists> + if (${beanName}.get${pkBeanName}() == null) { + ${beanName}.set${clist.columnUName}(this.find${beanName}POSeqNextVal()); + } + + + + StringBuffer sql = new StringBuffer("INSERT INTO ${tableName}(" + "${column_list_str}" + ") VALUES ("); + StringBuffer sqlI = new StringBuffer("INSERT INTO ${tableName}("); + StringBuffer sqlC = new StringBuffer(") VALUES ("); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + <#if columnList?exists> + <#list columnList as clist> + if(${beanName}.get${clist.columnUName}() != null){ + sqlI.append("${clist.columnName},"); + sqlC.append(" ?, "); + pql.append(${beanName}.get${clist.columnUName}() + ", "); + list.add(${beanName}.get${clist.columnUName}()); + } + + + + + int count = 0; + try { + jdbcegroceryWrite.update(StringUtil.removeLast(StringUtil.removeLast(sqlI.toString())+sqlC.toString()) + ")", list.toArray()); + count = jdbcegroceryWrite.queryForInt("SELECT LAST_INSERT_ID()"); + return count; + } catch (Exception e) { + LogUtils.error("error:", logger, e, StringUtil.removeLast(pql.toString()) + ")", null); + } finally { + Date endtime = new Date(); + LogUtils.info("info:", logger, + "${beanName}Dao.add${beanName}PO (${beanName}PO ${beanName})\n" + + "执行SQL:" + StringUtil.removeLast(pql.toString()) + ")" + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return -1; + } + /** + * 批量添加 + */ + public int add${beanName}POList(List<${beanName}PO> ${beanName}list) { + Date starttime = new Date(); + int count = 0; + for (${beanName}PO ${beanName} : ${beanName}list) { + count += add${beanName}PO(${beanName}); + } + Date endtime = new Date(); + LogUtils.info("info:", logger, + "${beanName}Dao.add${beanName}POList(List<${beanName}PO> ${beanName}list)\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + return count; + } + /** + * 按ID删除 + */ + public int delete${beanName}POByID(${pkType} id) { + Date starttime = new Date(); + StringBuffer sql = new StringBuffer("DELETE FROM ${tableName} WHERE"); + StringBuffer pql = new StringBuffer(sql.toString()); + pql.append(" ${pkColumName} = " + id); + sql.append(" ${pkColumName} = ?"); + int count = 0; + try { + count = jdbcegroceryWrite.update(sql.toString(), id); + return count; + } catch (Exception e) { + LogUtils.error("error:", logger, e, pql.toString(), null); + } finally { + Date endtime = new Date(); + LogUtils.info("info:", logger, + "${beanName}Dao.delete${beanName}POByID(${pkType} id)\n" + + "执行SQL:" + pql.toString() + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return -1; + } + /** + * 删除按List条件 + * Object[]数组长度是3 + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public int delete${beanName}POByCondition(List condition) { + if (null == condition || condition.size() == 0) { + LogUtils.error("error:", logger, new Exception("请求条件异常,请求条件List condition不能为空!"), null, null); + return -1; + } + if (StringUtil.isAutowired(condition)) { + LogUtils.error("error:", logger, new Exception("请求条件异常,无效请求!"), null, null); + return -1; + } + Date starttime = new Date(); + List list = new ArrayList(); + StringBuffer sql = new StringBuffer("DELETE FROM ${tableName}"); + StringBuffer pql = new StringBuffer(sql.toString()); + JdbcUtil.appendWhereCondition(sql, pql, list, condition); + int count = 0; + try { + count = jdbcegroceryWrite.update( sql.toString(), list.toArray()); + return count; + } catch (Exception e) { + LogUtils.error("error:", logger, e, pql.toString(), null); + } finally { + Date endtime = new Date(); + LogUtils.info("cacheinfo:", logger, + "${beanName}Dao.delete${beanName}POByCondition(List condition)\n" + + "执行SQL:" + pql.toString() + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return -1; + } + + /** + * 删除按condition条件 + * 建议使用delete${beanName}POByCondition(List condition), 如果remove${beanName}POByCondition(List condition)满足不了where条件可以使用此方法。 + * condition为where后面的条件,condition不能为空。 + */ + public int delete${beanName}POBySql(String sqlCondition) { + if (StringUtil.isEmpty(sqlCondition)) { + LogUtils.error("error:", logger, new Exception("请求条件异常,请求条件String sqlCondition不能为空!"), null, null); + return -1; + } + if (StringUtil.isAutowired(sqlCondition)) { + LogUtils.error("error:", logger, new Exception("请求条件异常,无效请求!"), null, null); + return -1; + } + Date starttime = new Date(); + + StringBuffer sql = new StringBuffer("DELETE FROM ${tableName} WHERE "); + int count = 0; + try { + count = jdbcegroceryWrite.update( sql.toString() + sqlCondition); + return count; + } catch (Exception e) { + LogUtils.error("error:", logger, e, sql.toString() + sqlCondition, null); + } finally { + Date endtime = new Date(); + LogUtils.info("info", logger, + "${beanName}Dao.delete${beanName}POBySql(String sqlCondition)\n" + + "执行SQL:" + sql.toString() + sqlCondition + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return -1; + } + + /** + * 根据list对象逐个删除。 + */ + public int delete${beanName}POList(List<${beanName}PO> ${beanName}list) { + int count = 0; + for (${beanName}PO ${beanName} : ${beanName}list) { + count += delete${beanName}POByID(${beanName}.get${pkBeanName}()); + } + return count; + } + + /** + * 根据对象ID修改。 + */ + public int update${beanName}PO(${beanName}PO ${beanName}) { + if (null == ${beanName} || null == ${beanName}.get${pkBeanName}()) { + LogUtils.error("error:", logger, new Exception("请求条件异常,请求对象和对象ID不能为空!"), null, null); + return -1; + } + Date starttime = new Date(); + StringBuffer sql = new StringBuffer("UPDATE ${tableName} SET"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + <#if columnList?exists> + <#list columnList as clist> + <#if clist.seqName?exists> + <#else> + <#if clist.columnJAVAType = "Long" || clist.columnJAVAType = "Integer" || clist.columnJAVAType = "Short" || clist.columnJAVAType = "Float" || clist.columnJAVAType = "Double"> + boolean ${clist.columnUName}IsZero = false; + Object variation${clist.columnUName} = ${beanName}.getVariation${clist.columnUName}(); + if (variation${clist.columnUName} instanceof BigDecimal) { + ${clist.columnUName}IsZero = (((BigDecimal)variation${clist.columnUName}).compareTo(BigDecimal.ZERO) == 0); + } else { + Long l${clist.columnUName} = Long.parseLong(String.valueOf(variation${clist.columnUName})); + ${clist.columnUName}IsZero = (l${clist.columnUName} == 0); + } + if (!${clist.columnUName}IsZero) { + sql.append(" ${clist.columnName} = ${clist.columnName} + ?, "); + pql.append(" ${clist.columnName} = ${clist.columnName} + " + ${beanName}.getVariation${clist.columnUName}() + ","); + list.add(${beanName}.getVariation${clist.columnUName}()); + } else { + sql.append(" ${clist.columnName} = ?, "); + pql.append(" ${clist.columnName} = " + ${beanName}.get${clist.columnUName}() + ","); + list.add(${beanName}.get${clist.columnUName}()); + } + <#elseif clist.columnJAVAType = "java.math.BigDecimal"> + if (${beanName}.getVariation${clist.columnUName}().compareTo(BigDecimal.ZERO) != 0) { + sql.append(" ${clist.columnName} = ${clist.columnName} + ?, "); + pql.append(" ${clist.columnName} = ${clist.columnName} + " + ${beanName}.getVariation${clist.columnUName}() + ","); + list.add(${beanName}.getVariation${clist.columnUName}()); + } else { + sql.append(" ${clist.columnName} = ?, "); + pql.append(" ${clist.columnName} = " + ${beanName}.get${clist.columnUName}() + ","); + list.add(${beanName}.get${clist.columnUName}()); + } + <#else> + sql.append(" ${clist.columnName} = ?, "); + pql.append(" ${clist.columnName} = " + ${beanName}.get${clist.columnUName}() + ","); + list.add(${beanName}.get${clist.columnUName}()); + + + + + + String where = " WHERE ${pkColumName} = ?"; + String pwhere = " WHERE ${pkColumName} = " + ${beanName}.get${pkBeanName}(); + list.add(${beanName}.get${pkBeanName}()); + int count = 0; + try { + count = jdbcegroceryWrite.update(StringUtil.removeLast(sql.toString()) + where, list.toArray()); + return count; + } catch (Exception e) { + LogUtils.error("error:", logger, e, StringUtil.removeLast(pql.toString()) + pwhere, null); + } finally { + Date endtime = new Date(); + LogUtils.info("info", logger, + "${beanName}Dao.update${beanName}PO(${beanName}PO ${beanName})\n" + + "执行SQL:" + StringUtil.removeLast(pql.toString()) + pwhere + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return -1; + } + + /** + * 根据ID修改指定的值 + */ + public int update${beanName}FieldById(List changeList, ${pkType} id) { + if (null == id) { + LogUtils.error("error:", logger, new Exception("请求条件异常,请求对象和对象ID不能为空!"), null, null); + return -1; + } + Date starttime =new Date(); + StringBuffer sql = new StringBuffer("UPDATE ${tableName} SET"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + Map map = new HashMap(); + for (int i = 0, iLen = changeList.size(); i < iLen; i++) { + String name = (String) changeList.get(i)[0]; + Object value = changeList.get(i)[1]; + String variationOpt = "="; + if (changeList.get(i).length > 2) + variationOpt = (String)changeList.get(i)[2]; + if (variationOpt.equals("=")) { + sql.append(" " + name + " = ?,"); + list.add(value); + if (value == null) { + pql.append(" " + name + "=null,"); + } else { + pql.append(" " + name + "=\"" + value.toString() + "\","); + } + map.put(name, value); + } else { + sql.append(" " + name + " = " + name + " + ?,"); + list.add(value); + pql.append(" " + name + " = " + name + " + " + value.toString() + ","); + <#--会有问题 暂留 + map.put(name, value);--> + } + } + + String where = " WHERE ${pkColumName}=?"; + String pwhere = " WHERE ${pkColumName}=\"" + id + "\""; + list.add(id); + int count = 0; + try { + count = jdbcegroceryWrite.update(StringUtil.removeLast(sql.toString()) + where, list.toArray()); + return count; + } catch (Exception e) { + LogUtils.error("error:", logger, e, StringUtil.removeLast(pql.toString()) + pwhere, null); + } finally { + Date endtime = new Date(); + LogUtils.info("info", logger, + "${beanName}Dao.update${beanName}PO(List changeList, ${pkType} id)\n" + + "执行SQL:" + StringUtil.removeLast(pql.toString()) + pwhere + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return -1; + } + + /** + * 批量修改。 + */ + public int update${beanName}POList(List<${beanName}PO> ${beanName}list) { + int count = 0; + for (${beanName}PO ${beanName} : ${beanName}list) { + count += update${beanName}PO(${beanName}); + } + return count; + } + + /** + * List updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 + * List condition 修改的条件, 数组长度是3, 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 + */ + public int update${beanName}POByCondition(List updateObj, List condition) { + if (null == updateObj || updateObj.size() == 0) { + LogUtils.error("error:", logger, new Exception("请求条件异常,请求条件List updateObj不能为空!"), null, null); + return -1; + } + if (null == condition || condition.size() == 0) { + LogUtils.error("error:", logger, new Exception("请求条件异常,请求条件List condition不能为空!"), null, null); + return -1; + } + if (StringUtil.isAutowired(condition)) { + LogUtils.error("error:", logger, new Exception("请求条件异常,无效请求!"), null, null); + return -1; + } + Date starttime = new Date(); + StringBuffer sql = new StringBuffer("UPDATE ${tableName} SET"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + JdbcUtil.appendSql(sql, pql, list, updateObj); + StringBuffer where = new StringBuffer(""); + StringBuffer pwhere = new StringBuffer(""); + JdbcUtil.appendWhereCondition(where, pwhere, list, condition); + int count = 0; + try { + count = jdbcegroceryWrite.update(StringUtil.removeLast(sql.toString()) + where.toString(), list.toArray()); + return count; + } catch (Exception e) { + LogUtils.error("error:", logger, e, StringUtil.removeLast(pql.toString())+pwhere.toString(), null, null); + } finally { + Date endtime = new Date(); + LogUtils.info("info", logger, + "${beanName}Dao.update${beanName}POByCondition(List updateObj, List condition)\n" + + "执行SQL:" + StringUtil.removeLast(pql.toString())+pwhere.toString() + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return -1; + } + + /** + * List updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 + * String sqlCondition 修改的条件。 + */ + public int update${beanName}POBySql(List updateObj, String sqlCondition) { + if (null == updateObj || updateObj.size() == 0) { + LogUtils.error("error:", logger, new Exception("请求条件异常,请求条件List updateObj不能为空!"), null, null); + return -1; + } + if (StringUtil.isEmpty(sqlCondition)) { + LogUtils.error("error:", logger, new Exception("请求条件异常,请求条件sqlCondition不能为空!"), null, null); + return -1; + } + if (StringUtil.isAutowired(sqlCondition)) { + LogUtils.error("error:", logger, new Exception("请求条件异常,无效请求!"), null, null); + return -1; + } + Date starttime = new Date(); + StringBuffer sql = new StringBuffer("UPDATE ${tableName} SET"); + StringBuffer pql = new StringBuffer(sql.toString()); + List list = new ArrayList(); + JdbcUtil.appendSql(sql, pql, list, updateObj); + int count = 0; + try { + count = jdbcegroceryWrite.update(StringUtil.removeLast(sql.toString()) + " WHERE "+sqlCondition, list.toArray()); + return count; + } catch (Exception e) { + LogUtils.error("error:", logger, e, StringUtil.removeLast(pql.toString()) + " WHERE " + sqlCondition, null, null); + } finally { + Date endtime = new Date(); + LogUtils.info("info", logger, + "${beanName}Dao.update${beanName}POBySql(List updateObj, String sqlCondition)\n" + + "执行SQL:" + StringUtil.removeLast(pql.toString()) + " WHERE " + sqlCondition + "\n" + + "方法执行时长:" + (endtime.getTime()-starttime.getTime()) + "毫秒, 影响记录数:" + count + "(" + + StringUtil.dateToFormatStr(starttime, "yyyy-MM-dd HH:mm:ss.SSS") + + "*-*" + + StringUtil.dateToFormatStr(endtime, "yyyy-MM-dd HH:mm:ss.SSS") + + ")"); + } + return -1; + } +} \ No newline at end of file diff --git a/src/com/taover/base/template/HtmlLayuiTemplate.ftl b/src/com/taover/base/template/HtmlLayuiTemplate.ftl new file mode 100644 index 0000000..7b66a80 --- /dev/null +++ b/src/com/taover/base/template/HtmlLayuiTemplate.ftl @@ -0,0 +1,398 @@ + + + + + 八爪云ERP系统 + + + + + + + + +
+
+ + +
+
+ <#list fields as tempField> + ${tempField["layui-search-item"]} + + +
+ +
+
+
+ + +
+
+ + +
+ +
+ + +
+
+
+ + +
+ <#list fields as tempField> + <#if (tempField["name"]!="id")> + ${tempField["layui-form-item"]} + + + +
+
+ + +
+
+
+ + +
+ <#list fields as tempField> + ${tempField["layui-form-item"]} + + +
+
+ + +
+
+
+ + + + + + + + diff --git a/src/com/taover/base/template/HtmlTemplate.ftl b/src/com/taover/base/template/HtmlTemplate.ftl new file mode 100644 index 0000000..9cb0a56 --- /dev/null +++ b/src/com/taover/base/template/HtmlTemplate.ftl @@ -0,0 +1,58 @@ +
+
+
+
+
+ +
+
+ <#list fields as tempField> + ${tempField["easyui-search-item"]} + + + 查询 + +
+
+ 添加 + 删除 +
+
+ + +
+ + <#list fields as tempField> + <#if (tempField["name"]!="id")> + + + + + + +
${tempField["cnName"]}:
+
+ +
+ + <#list fields as tempField> + + + + + +
${tempField["cnName"]}:
+
+ + diff --git a/src/com/taover/base/template/JsTemplate.ftl b/src/com/taover/base/template/JsTemplate.ftl new file mode 100644 index 0000000..f114621 --- /dev/null +++ b/src/com/taover/base/template/JsTemplate.ftl @@ -0,0 +1,33 @@ +$(function(){ + var controllerPathMap = "${controllerPathMap}"; + var addDialogId = controllerPathMap+"_add"; + var editDialogId = controllerPathMap+"_edit"; + var gridId = controllerPathMap+"_list"; + var gridToolbarId = controllerPathMap+"_toolbar" + var gridColumns = [{ + field: 'selectedItem', + checkbox: true + }, + <#list fields as tempField> + <#if tempField["name"] != "id"> + { + field: '${tempField["name"]}', + title: '${tempField["cnName"]}', + sortable: true, + }, + + + { + field : 'id', + title : '操作', + width : 10, + formatter : function(value, rows, index){ + return '修改 | ' + + '删除'; + }, + }, + ]; + + ${controllerPathMap}Page = tabInit(controllerPathMap, addDialogId, editDialogId, gridId, gridToolbarId, gridColumns); +}); + diff --git a/src/com/taover/base/template/POTemplate.ftl b/src/com/taover/base/template/POTemplate.ftl new file mode 100644 index 0000000..5f43059 --- /dev/null +++ b/src/com/taover/base/template/POTemplate.ftl @@ -0,0 +1,75 @@ +<#--包名 --> +package ${packages} +import java.util.HashMap; +import java.util.Map; +import java.io.Serializable; +/** + <#if version?exists> + * @version ${version} + + */ + + public class ${name}PO implements Serializable { + + <#--变量 ,get,set方法--> +<#if tablemodel.columnlist?exists> + <#list tablemodel.columnlist as clist> + private ${clist.columnJAVAType} ${clist.columnName}; + + <#if clist.columnRemarks?exists> + /** + * ${clist.columnRemarks} + */ + <#else> + + <#if clist.columnJAVAType = "java.sql.Timestamp" > + @org.codehaus.jackson.map.annotate.JsonSerialize(using = com.taover.tools.DateTimeSerializer.class) + + <#if clist.columnJAVAType = "java.util.Date" > + @org.codehaus.jackson.map.annotate.JsonSerialize(using = com.taover.tools.DateSerializer.class) + + public ${clist.columnJAVAType} get${clist.columnMethodName}(){ + return ${clist.columnName}; + } + + public void set${clist.columnMethodName}(${clist.columnJAVAType} ${clist.columnName}){ + this.${clist.columnName} = ${clist.columnName}; + } + + <#if clist.columnJAVAType = "Long" || clist.columnJAVAType = "java.math.BigDecimal" || clist.columnJAVAType = "Integer" || clist.columnJAVAType = "Short" || clist.columnJAVAType = "Float" || clist.columnJAVAType = "Double"> + <#if clist.columnJAVAType = "Long"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0L; + + <#if clist.columnJAVAType = "java.math.BigDecimal"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = new java.math.BigDecimal(0.0); + + <#if clist.columnJAVAType = "Integer"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0; + + <#if clist.columnJAVAType = "Short"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0; + + <#if clist.columnJAVAType = "Double"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0d; + + <#if clist.columnJAVAType = "Float"> + private ${clist.columnJAVAType} variation${clist.columnMethodName} = 0f; + + public ${clist.columnJAVAType} getVariation${clist.columnMethodName}(){ + return variation${clist.columnMethodName}; + } + + public void setVariation${clist.columnMethodName}(${clist.columnJAVAType} variation${clist.columnName}){ + this.variation${clist.columnMethodName} = variation${clist.columnName}; + } + + + + + + + @Override + public String toString() { + return "${name}PO: ${toStringMethodBody}; + } + } \ No newline at end of file diff --git a/src/com/taover/base/template/ServiceExportTemplate.ftl b/src/com/taover/base/template/ServiceExportTemplate.ftl new file mode 100644 index 0000000..fa39405 --- /dev/null +++ b/src/com/taover/base/template/ServiceExportTemplate.ftl @@ -0,0 +1,21 @@ +package ${mainPackageInfo}.${moduleName}.export; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.Resource; + +import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Service; + +import com.taover.base.ResultInfo; +import ${mainPackageInfo}.contants.ResultInfoCode; +import ${mainPackageInfo}.utils.UtilsString; +import ${mainPackageInfo}.utils.UtilsSql; + +@Service +public class ${moduleNameFirstBig}ExportService{ + +} diff --git a/src/com/taover/base/template/ServiceImplTemplate.ftl b/src/com/taover/base/template/ServiceImplTemplate.ftl new file mode 100644 index 0000000..4e674aa --- /dev/null +++ b/src/com/taover/base/template/ServiceImplTemplate.ftl @@ -0,0 +1,111 @@ +package ${mainPackageInfo}.${moduleName}.service.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.Resource; + +import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Service; + +import com.taover.base.ResultInfo; +import ${mainPackageInfo}.contants.ResultInfoCode; +import ${mainPackageInfo}.utils.UtilsString; +import ${mainPackageInfo}.utils.UtilsSql; +import ${mainPackageInfo}.${moduleName}.service.${beanClassName}Service; + +import ${poPackageInfo}.${beanClassName}Dao; +import ${poPackageInfo}.${beanClassName}PO; + +@Service +public class ${beanClassName}ServiceImpl implements ${beanClassName}Service{ + @Resource + private ${beanClassName}Dao ${beanFieldName}Dao; + + @Override + public ResultInfo add(${beanClassName}PO ${beanFieldName}PO){ + //创建返回对象 + ResultInfo result = new ResultInfo(); + + //调用Service方法 + int addResult = this.${beanFieldName}Dao.add${beanClassName}PO(${beanFieldName}PO); + + if(addResult < 1){ + result.setResultId(ResultInfoCode.RESULTID_FAILURE_210); + result.setResultMessage("添加失败"); + }else{ + result.setResultId(ResultInfoCode.RESULTID_SUCCESS_200); + result.setResultMessage("添加成功"); + } + return result; + } + + @Override + public ResultInfo delete(String ids){ + //创建返回对象 + ResultInfo result = new ResultInfo(); + + //参数检验 + if(ids == null || ids.length() == 0){ + result.setResultId(ResultInfoCode.RESULTID_FAILURE_210); + result.setResultMessage("删除失败,缺少主键信息"); + return result; + } + + Integer[] idsArray = UtilsString.transIdStringToArray(ids, ","); + if(idsArray == null || idsArray.length == 0){ + result.setResultId(ResultInfoCode.RESULTID_FAILURE_210); + result.setResultMessage("删除失败,缺少主键信息"); + return result; + } + + String idsCondition = " id in(" + idsArray[0]; + for(int i=1; i query(List arrayCondition, String sort, String order, int page, int pageSize){ + String sortCondition = UtilsSql.getSortCondition(sort, order, null); + return this.${beanFieldName}Dao.findPageByCondition(arrayCondition, sortCondition, page, pageSize, false); + } +} diff --git a/src/com/taover/base/template/ServiceTemplate.ftl b/src/com/taover/base/template/ServiceTemplate.ftl new file mode 100644 index 0000000..1bbe035 --- /dev/null +++ b/src/com/taover/base/template/ServiceTemplate.ftl @@ -0,0 +1,37 @@ +package ${mainPackageInfo}.${moduleName}.service; + +import java.util.List; +import java.util.Map; + +import com.taover.base.ResultInfo; + +import ${poPackageInfo}.${beanClassName}PO; + +public interface ${beanClassName}Service { + /** + * 业务层添加接口 + */ + public ResultInfo add(${beanClassName}PO ${beanFieldName}PO); + + /** + * 业务层删除接口 + */ + public ResultInfo delete(String ids); + + /** + * 业务层更新接口 + */ + public ResultInfo edit(${beanClassName}PO ${beanFieldName}PO); + + /** + * 依据arrayCondition查询条件查询单条记录,如果存在多条记录,则取第一条 + * @param arrayCondition + * @param sort + * @param order + * @param page + * @param pageSize + * @return 返回实体引用,如果未找到返回null + */ + public Map query(List arrayCondition, String sort, String order, int page, int pageSize); + +} diff --git a/src/com/taover/base/template/Temp.ftl b/src/com/taover/base/template/Temp.ftl new file mode 100644 index 0000000..847844e --- /dev/null +++ b/src/com/taover/base/template/Temp.ftl @@ -0,0 +1,8 @@ +//${cnFunc} +//${enFunc} +<#list propertyList as property > +var ${property} = getNumberBoxValue('${property}', 0); + + +var ${enFunc}; +$('#${result}').numberbox('setValue', ${result}); \ No newline at end of file diff --git a/src/com/taover/base/template/createTableTemplate.ftl b/src/com/taover/base/template/createTableTemplate.ftl new file mode 100644 index 0000000..eb8e89f --- /dev/null +++ b/src/com/taover/base/template/createTableTemplate.ftl @@ -0,0 +1,31 @@ +-- Create table +create table ${tableName} +( +<#list columnlist as clist> + ${clist.columnName} ${clist.columnSQLType}<#if clist.columnSize?exists>${clist.columnSize}<#if clist.columnDefaults?exists && clist.columnDefaults != '' && clist.columnDefaults != 'null'> default ${clist.columnDefaults}<#if !clist.nullable> not null<#if clist_has_next>, + +); +<#if tableRemarks?exists> +-- Add comments to the table +comment on table ${tableName} is '${tableRemarks}'; + +-- Add comments to the columns +<#list columnlist as clist> + <#if clist.columnRemarks?exists && clist.columnRemarks != clist.columnName> +comment on column ${tableName}.${clist.columnName} is '${clist.columnRemarks}'; + + +<#if tablePk?exists> +-- Create index +CREATE UNIQUE INDEX PK_${tableName} ON ${tableName}(${tablePk}); +ALTER TABLE ${tableName} ADD + PRIMARY KEY (${tablePk}) + USING INDEX PK_${tableName}; + +-- Create sequence +create sequence SEQ_${tableName}<#if tableName?length lt 24>_PK +minvalue 1 +maxvalue 99999999999999999 +start with 1 +increment by 1 +cache 20; diff --git a/src/com/taover/base/template/model/.svn/entries b/src/com/taover/base/template/model/.svn/entries new file mode 100644 index 0000000..b91befe --- /dev/null +++ b/src/com/taover/base/template/model/.svn/entries @@ -0,0 +1,37 @@ +10 + +dir +115305 +svn://119.254.17.138/repos/%E6%B2%B1%E6%B2%B1%E7%94%9F%E6%B4%BB%E7%BD%91%E8%B6%85/code/soa.tootoo.cn/trunk/generate-tootoo-dao-po/src/cn/tootoo/base/template/model +svn://119.254.17.138/repos + + + +2014-10-16T09:45:05.710295Z +76282 +zhuruisong + + +svn:special svn:externals svn:needs-lock + + + + + + + + + + + +5351f05e-98f4-42cc-8e6a-33022518c94f + +createTable +dir + +dao +dir + +po +dir + diff --git a/src/com/taover/base/template/model/bussiness/ControllerModel.java b/src/com/taover/base/template/model/bussiness/ControllerModel.java new file mode 100644 index 0000000..ff2b968 --- /dev/null +++ b/src/com/taover/base/template/model/bussiness/ControllerModel.java @@ -0,0 +1,179 @@ +package com.taover.base.template.model.bussiness; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import com.taover.business.Utils; +import com.taover.db.TableColumn; +import com.taover.tools.StringUtil; + +public class ControllerModel { + private String mainPackageInfo; + private String dbPackageInfo; + private String poClassName; + private String poFieldName; + private String serviceImplClassName; + private String serviceImplFieldName; + private String controllerClassName; + private String moduleName; + private String moduleNameFirstBig; + private String controllerUri; + private List> fields = new ArrayList>(); + + private ControllerModel(){} + public static ControllerModel createControllerModel(String packageInfo, String poPackageInfo, String serviceImplPackageInfo, String beanClassName, String mainPackageInfo, String moduleName, Vector tableColumns){ + ControllerModel model = new ControllerModel(); + model.moduleName = moduleName; + model.mainPackageInfo = mainPackageInfo; + model.dbPackageInfo = poPackageInfo; + model.poClassName = beanClassName+"PO"; + model.controllerUri = beanClassName.toLowerCase(); + model.poFieldName = Utils.getFirstLetterLower(model.poClassName); + model.serviceImplClassName = beanClassName + "Service"; + model.serviceImplFieldName = Utils.getFirstLetterLower(model.serviceImplClassName); + model.controllerClassName = beanClassName + "Controller"; + model.moduleNameFirstBig = moduleName.toUpperCase().substring(0, 1)+moduleName.substring(1); + + for(TableColumn column : tableColumns){ + String fieldName = column.getColumnName(); + String varName = column.getColumBeanLName(); + String fieldType = column.getJAVADataType(); + + Map columnMap = new HashMap(); + String conditionCode = ""; + if("java.util.Date|java.sql.Time|java.sql.Timestamp".indexOf(fieldType) != -1){ + conditionCode = ControllerModel.parseConditionDate(varName, fieldName); + }else if("Byte|Long|Integer|Short".indexOf(fieldType) != -1){ + conditionCode = ControllerModel.parseConditionNumber(varName, fieldName); + }else{ + conditionCode = ControllerModel.parseConditionString(varName, fieldName); + } + columnMap.put("conditionCode", conditionCode); + model.fields.add(columnMap); + } + + return model; + } + + /** + * + String toList = request.getParameter("to"); + if(StringUtils.isNotEmpty(toList)){ + arrayCondition.add(new Object[]{"to_list", "like", "%"+toList+"%"}); + } + * @param name + * @return + */ + public static String parseConditionString(String name, String fieldName){ + String lowName = StringUtil.formatBeanNameFirstLow(name); + String sqlCondition = "String "+lowName+" = request.getParameter(\""+lowName+"\");\n" + +"\t\tif(StringUtils.isNotEmpty("+lowName+")){ \n" + +"\t\t\tarrayCondition.add(new Object[]{\""+fieldName+"\", \"like\", \"%\"+"+lowName+"+\"%\"}); \n" + +"\t\t}\n"; + return sqlCondition; + } + + /** + * + String toList = request.getParameter("to"); + if(StringUtils.isNotEmpty(toList) && StringUtils.isNumeric(toList)){ + arrayCondition.add(new Object[]{"to_list", "like", "%"+toList+"%"}); + } + * @param name + * @return + */ + public static String parseConditionNumber(String name, String fieldName){ + String lowName = StringUtil.formatBeanNameFirstLow(name); + String sqlCondition = "String "+lowName+" = request.getParameter(\""+lowName+"\");\n" + +"\t\tif(StringUtils.isNotEmpty("+lowName+") && StringUtils.isNumeric("+lowName+") ){ \n" + +"\t\t\tarrayCondition.add(new Object[]{\""+fieldName+"\", \"=\", "+lowName+"}); \n" + +"\t\t}\n"; + return sqlCondition; + } + + /** + * + String date = request.getParameter("date"); + if(StringUtils.isNotEmpty(date)){ + String[] dateGap = date.split("+-+"); + if(dateGap.length == 1){ + arrayCondition.add(new Object[]{" datediff(`date`, '"+dateGap[0]+"')>=0 ", null}); + }else if(dateGap.length == 2){ + arrayCondition.add(new Object[]{"( datediff(`date`, '"+dateGap[0]+"')>=0 and datediff(`date`, '"+dateGap[1]+"')<=0 )", null}); + } + } + * @param name + * @return + */ + public static String parseConditionDate(String name, String fieldName){ + String lowName = StringUtil.formatBeanNameFirstLow(name); + String sqlCondition = "String "+lowName+" = request.getParameter(\""+lowName+"\");\n" + + "\t\tif(StringUtils.isNotEmpty("+lowName+")){\n" + + "\t\t\tString[] dateGap = "+lowName+".split(\"+-+\");\n" + + "\t\t\tif(dateGap.length == 1){\n" + +"\t\t\t\tarrayCondition.add(new Object[]{\" datediff(`"+fieldName+"`, '\"+dateGap[0]+\"')>=0 \", null});\n" + + "\t\t\t}else if(dateGap.length == 2){ \n" + +"\t\t\t\tarrayCondition.add(new Object[]{\"( datediff(`"+fieldName+"`, '\"+dateGap[0]+\"')>=0 and datediff(`"+fieldName+"`, '\"+dateGap[1]+\"')<=0 )\", null});\n" + +"\t\t\t}\n" + +"\t\t}\n"; + return sqlCondition; + } + + public String getControllerUri() { + return controllerUri; + } + public String getMainPackageInfo() { + return mainPackageInfo; + } + public void setMainPackageInfo(String packageInfo) { + this.mainPackageInfo = packageInfo; + } + public String getPoPackageInfo() { + return dbPackageInfo; + } + public void setPoPackageInfo(String poPackageInfo) { + this.dbPackageInfo = poPackageInfo; + } + public String getPoClassName() { + return poClassName; + } + public void setPoClassName(String poClassName) { + this.poClassName = poClassName; + } + public String getPoFieldName() { + return poFieldName; + } + public void setPoFieldName(String poFieldName) { + this.poFieldName = poFieldName; + } + public String getServiceImplClassName() { + return serviceImplClassName; + } + public void setServiceImplClassName(String serviceImplClassName) { + this.serviceImplClassName = serviceImplClassName; + } + public String getServiceImplFieldName() { + return serviceImplFieldName; + } + public void setServiceImplFieldName(String serviceImplFieldName) { + this.serviceImplFieldName = serviceImplFieldName; + } + public String getControllerClassName() { + return controllerClassName; + } + public String getModuleName() { + return moduleName; + } + public String getModuleNameFirstBig() { + return moduleNameFirstBig; + } + public void setControllerClassName(String controllerClassName) { + this.controllerClassName = controllerClassName; + } + public List> getFields() { + return fields; + } +} diff --git a/src/com/taover/base/template/model/bussiness/EnvironmentModel.java b/src/com/taover/base/template/model/bussiness/EnvironmentModel.java new file mode 100644 index 0000000..269d04e --- /dev/null +++ b/src/com/taover/base/template/model/bussiness/EnvironmentModel.java @@ -0,0 +1,75 @@ +package com.taover.base.template.model.bussiness; + +import java.io.File; + +public class EnvironmentModel { + private String controllerPackageInfo; + private String poPackageInfo; + private String servicePackageInfo; + private String controllerFilePath; + private String serviceFilePath; + private String beanClassName; + private String mainPackageInfo; + private String subModuleName; + + private EnvironmentModel(){} + public static EnvironmentModel createEnvironmentModel(String modulePackageInfo, String moduleFilePath, String poPackageInfo, String beanClassName, String subModuluName){ + EnvironmentModel envir = new EnvironmentModel(); + envir.controllerPackageInfo = modulePackageInfo + "." + subModuluName + "." +"controller"; + envir.poPackageInfo = poPackageInfo; + envir.servicePackageInfo = modulePackageInfo + "." + subModuluName + "." +"service"; + envir.controllerFilePath = moduleFilePath + File.separator + subModuluName + File.separator +"controller"; + envir.serviceFilePath = moduleFilePath + File.separator + subModuluName + File.separator+"service"; + envir.beanClassName = beanClassName; + envir.mainPackageInfo = modulePackageInfo; + envir.subModuleName = subModuluName; + return envir; + } + + public String getControllerPackageInfo() { + return controllerPackageInfo; + } + public void setControllerPackageInfo(String controllerPackageInfo) { + this.controllerPackageInfo = controllerPackageInfo; + } + public String getPoPackageInfo() { + return poPackageInfo; + } + public void setPoPackageInfo(String poPackageInfo) { + this.poPackageInfo = poPackageInfo; + } + public String getServicePackageInfo() { + return servicePackageInfo; + } + public void setServicePackageInfo(String servicePackageInfo) { + this.servicePackageInfo = servicePackageInfo; + } + public String getControllerFilePath() { + return controllerFilePath; + } + public void setControllerFilePath(String controllerFilePath) { + this.controllerFilePath = controllerFilePath; + } + public String getServiceFilePath() { + return serviceFilePath; + } + public void setServiceFilePath(String serviceFilePath) { + this.serviceFilePath = serviceFilePath; + } + public String getBeanClassName() { + return beanClassName; + } + public void setBeanClassName(String beanClassName) { + this.beanClassName = beanClassName; + } + public String getMainPackageInfo() { + return mainPackageInfo; + } + public String getSubModuleName() { + return subModuleName; + } + public void setUtilPackageInfo(String utilPackageInfo) { + this.mainPackageInfo = utilPackageInfo; + } + +} diff --git a/src/com/taover/base/template/model/bussiness/ServiceModel.java b/src/com/taover/base/template/model/bussiness/ServiceModel.java new file mode 100644 index 0000000..f826ead --- /dev/null +++ b/src/com/taover/base/template/model/bussiness/ServiceModel.java @@ -0,0 +1,53 @@ +package com.taover.base.template.model.bussiness; + +import com.taover.business.Utils; + +public class ServiceModel { + private String poPackageInfo; + private String beanClassName; + private String beanFieldName; + private String mainPackageInfo; + private String moduleName; + private String moduleNameFirstBig; + + private ServiceModel(){} + public static ServiceModel createServiceModel(String poPackageInfo, String beanClassName, String mainPackageInfo, String moduleName){ + ServiceModel model = new ServiceModel(); + model.poPackageInfo = poPackageInfo; + model.beanClassName = beanClassName; + model.beanFieldName = Utils.getFirstLetterLower(beanClassName); + model.mainPackageInfo = mainPackageInfo; + model.moduleName = moduleName; + model.moduleNameFirstBig = moduleName.toUpperCase().substring(0, 1)+moduleName.substring(1); + return model; + } + public String getMainPackageInfo() { + return mainPackageInfo; + } + public String getPoPackageInfo() { + return poPackageInfo; + } + public void setPoPackageInfo(String poPackageInfo) { + this.poPackageInfo = poPackageInfo; + } + public String getBeanClassName() { + return beanClassName; + } + public void setBeanClassName(String beanClassName) { + this.beanClassName = beanClassName; + } + public String getBeanFieldName() { + return beanFieldName; + } + public String getModuleName() { + return moduleName; + } + public String getModuleNameFirstBig() { + return moduleNameFirstBig; + } + public void setBeanFieldName(String beanFieldName) { + this.beanFieldName = beanFieldName; + } + + +} diff --git a/src/com/taover/base/template/model/bussiness/ViewModel.java b/src/com/taover/base/template/model/bussiness/ViewModel.java new file mode 100644 index 0000000..c1db03f --- /dev/null +++ b/src/com/taover/base/template/model/bussiness/ViewModel.java @@ -0,0 +1,331 @@ +package com.taover.base.template.model.bussiness; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import com.taover.db.TableColumn; + +public class ViewModel { + private String webRootPath; + private String controllerPathMap; + //map结构如下 + //name:"",easyui:"numberbox|validatebox|datetimebox",required:true|false,precision:0,min:0,max:32767,validType + private List> fields = new ArrayList>(); + + private ViewModel(){} + public static ViewModel createViewModel(String controllerPathMap, String webRootPath,Vector tableColumns){ + ViewModel model = new ViewModel(); + model.controllerPathMap = controllerPathMap; + model.webRootPath = webRootPath; + for(TableColumn column : tableColumns){ + String fieldName = column.getColumBeanLName(); + String fieldType = column.getJAVADataType(); + + Map columnMap = new HashMap(); + columnMap.put("name", fieldName); + if("Byte|Long|Integer|Short".indexOf(fieldType) != -1){ + columnMap.put("easyui", "numberbox"); + columnMap.put("attr", " precision=\"0\" "); + }else if("Float|Double".indexOf(fieldType) != -1){ + columnMap.put("easyui", "numberbox"); + columnMap.put("attr", " precision=\"2\" "); + }else if("java.util.Date|java.sql.Time|java.sql.Timestamp".indexOf(fieldType) != -1){ + columnMap.put("easyui", "datetimebox"); + columnMap.put("attr", ""); + }else{ + columnMap.put("easyui", "validatebox"); + columnMap.put("attr", " validType=\"length[0,"+column.getColumnSize()+"]\""); + } + if(!column.isNullable()){ + columnMap.put("required", " required=\"true\" "); + } + String remarks = column.getRemarks(); + String splitStr = ":"; + if(remarks.contains(":")){ + splitStr = ":"; + } + String remarkPart[] = remarks.split(splitStr); + String cnName = fieldName; + if(remarkPart.length > 0){ + cnName = remarkPart[0]; + } + columnMap.put("cnName", cnName); + + String easyuiSearchDom = ""; + String layuiSearchDom = ""; + String layuiFormDom = ""; + if(remarkPart.length > 1){ + easyuiSearchDom = ViewModel.parseEasyuiSearchSelect(fieldName, cnName, remarkPart[1]); + layuiSearchDom = ViewModel.parseLayuiSearchSelect(fieldName, cnName, remarkPart[1]); + layuiFormDom = ViewModel.parseLayuiFormSelect(fieldName, cnName, remarkPart[1]); + }else if("java.util.Date|java.sql.Time|java.sql.Timestamp".indexOf(fieldType) != -1){ + easyuiSearchDom = ViewModel.parseEasyuiSearchDatetime(fieldName, cnName); + layuiSearchDom = ViewModel.parseLayuiSearchDatetime(fieldName, cnName); + layuiFormDom = ViewModel.parseLayuiFormDatetime(fieldName, cnName); + }else if("Byte|Long|Integer|Short".indexOf(fieldType) != -1){ + easyuiSearchDom = ViewModel.parseEasyuiSearchNumber(fieldName, cnName); + layuiSearchDom = ViewModel.parseLayuiSearchNumber(fieldName, cnName); + layuiFormDom = ViewModel.parseLayuiFormNumber(fieldName, cnName); + }else{ + easyuiSearchDom = ViewModel.parseEasyuiSearchText(fieldName, cnName); + layuiSearchDom = ViewModel.parseLayuiSearchText(fieldName, cnName); + layuiFormDom = ViewModel.parseLayuiFormText(fieldName, cnName); + } + //构造easyui筛选栏元素 + columnMap.put("easyui-search-item", easyuiSearchDom); + + //构造layui筛选栏元素 + columnMap.put("layui-search-item", layuiSearchDom); + + //构造layui表单栏元素 + columnMap.put("layui-form-item", layuiFormDom); + + //构造layui表格表头 + columnMap.put("layui-table-item", ViewModel.parseLayuiTableHeader(fieldName, cnName)); + + model.fields.add(columnMap); + } + return model; + } + + public static String parseEasyuiSearchSelect(String name, String cnName, String optionStr){ + String easyuiSearchEle = "
" + + ""+cnName+"" + + "
"; + return easyuiSearchEle; + } + + public static String parseEasyuiSearchDatetime(String name, String cnName){ + String dateBoxDom = "
" + + ""+cnName+"" + + "" + + "
"; + return dateBoxDom; + } + + public static String parseEasyuiSearchNumber(String name, String cnName){ + String dateBoxDom = "
" + + ""+cnName+"" + + "" + + "
"; + return dateBoxDom; + } + + public static String parseEasyuiSearchText(String name, String cnName){ + String dateBoxDom = "
" + + ""+cnName+"" + + "" + + "
"; + return dateBoxDom; + } + + /** + *
+ +
+ +
+
+ * @param name + * @param cnName + * @param optionStr + * @return + */ + public static String parseLayuiSearchSelect(String name, String cnName, String optionStr){ + String LayuiSearchEle = "
" + + "" + + "
" + + "
"; + return LayuiSearchEle; + } + + /** + *
+ +
+ +
+
+ * @param name + * @param cnName + * @return + */ + public static String parseLayuiSearchDatetime(String name, String cnName){ + String dateBoxDom = "
" + + "" + + "
" + +"" + + "
"; + return dateBoxDom; + } + + public static String parseLayuiSearchNumber(String name, String cnName){ + String dateBoxDom = "
" + + "" + + "
" + +"" + + "
"; + return dateBoxDom; + } + + public static String parseLayuiSearchText(String name, String cnName){ + String dateBoxDom = "
" + + "" + + "
" + +"" + + "
"; + return dateBoxDom; + } + + public static String parseLayuiFormSelect(String name, String cnName, String optionStr){ + String LayuiFormEle = "
" + + "" + + "
" + + "
"; + return LayuiFormEle; + } + + /** + *
+ +
+ +
+
+ * @param name + * @param cnName + * @return + */ + public static String parseLayuiFormDatetime(String name, String cnName){ + String dateBoxDom = "
" + + "" + + "
" + +"" + + "
"; + return dateBoxDom; + } + + public static String parseLayuiFormNumber(String name, String cnName){ + String dateBoxDom = "
" + + "" + + "
" + +"" + + "
"; + return dateBoxDom; + } + + public static String parseLayuiFormText(String name, String cnName){ + String dateBoxDom = "
" + + "" + + "
" + +"" + + "
"; + return dateBoxDom; + } + + public static String parseLayuiTableHeader(String name, String cnName){ + String header = "{title:'"+cnName+"', field:'"+name+"', width:100, sort: true},"; + return header; + } + + public String getControllerPathMap() { + return controllerPathMap; + } + public void setControllerPathMap(String controllerPathMap) { + this.controllerPathMap = controllerPathMap; + } + public List> getFields() { + return fields; + } + public void setColumns(List> fields) { + this.fields = fields; + } +} diff --git a/src/com/taover/base/template/model/createTable/.svn/entries b/src/com/taover/base/template/model/createTable/.svn/entries new file mode 100644 index 0000000..e82af2c --- /dev/null +++ b/src/com/taover/base/template/model/createTable/.svn/entries @@ -0,0 +1,96 @@ +10 + +dir +115305 +svn://119.254.17.138/repos/%E6%B2%B1%E6%B2%B1%E7%94%9F%E6%B4%BB%E7%BD%91%E8%B6%85/code/soa.tootoo.cn/trunk/generate-tootoo-dao-po/src/cn/tootoo/base/template/model/createTable +svn://119.254.17.138/repos + + + +2014-10-16T09:45:05.710295Z +76282 +zhuruisong + + +svn:special svn:externals svn:needs-lock + + + + + + + + + + + +5351f05e-98f4-42cc-8e6a-33022518c94f + +ColumnModel.java +file + + + + +2015-08-10T05:52:55.776000Z +fe9f5f043f0f6fa96314ebb9e9d1814a +2014-10-14T09:23:57.914676Z +75944 +zhuruisong + + + + + + + + + + + + + + + + + + + + + +1421 + +TableModel.java +file + + + + +2015-08-10T05:52:55.753000Z +33b80ac378dbdff8b5833ca2b131b529 +2014-10-16T09:45:05.710295Z +76282 +zhuruisong + + + + + + + + + + + + + + + + + + + + + +913 + diff --git a/src/com/taover/base/template/model/createTable/.svn/text-base/ColumnModel.java.svn-base b/src/com/taover/base/template/model/createTable/.svn/text-base/ColumnModel.java.svn-base new file mode 100644 index 0000000..6608136 --- /dev/null +++ b/src/com/taover/base/template/model/createTable/.svn/text-base/ColumnModel.java.svn-base @@ -0,0 +1,64 @@ +package cn.tootoo.base.template.model.createTable; + +public class ColumnModel { + private String columnName; + private boolean nullable; + private String columnSQLType; + private String columnRemarks; + private String columnSize; + private String columnDefaults; + + public String getColumnName() { + return columnName; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public boolean isNullable() { + return nullable; + } + + public void setNullable(boolean nullable) { + this.nullable = nullable; + } + + public String getColumnSQLType() { + return columnSQLType; + } + + public void setColumnSQLType(String columnSQLType) { + this.columnSQLType = columnSQLType; + } + + public String getColumnRemarks() { + return columnRemarks; + } + + public void setColumnRemarks(String columnRemarks) { + this.columnRemarks = columnRemarks; + } + + + public String getColumnSize() { + return columnSize; + } + + + public void setColumnSize(String columnSize) { + this.columnSize = columnSize; + } + + + public String getColumnDefaults() { + return columnDefaults; + } + + + public void setColumnDefaults(String columnDefaults) { + this.columnDefaults = columnDefaults; + } + + +} diff --git a/src/com/taover/base/template/model/createTable/.svn/text-base/TableModel.java.svn-base b/src/com/taover/base/template/model/createTable/.svn/text-base/TableModel.java.svn-base new file mode 100644 index 0000000..445b579 --- /dev/null +++ b/src/com/taover/base/template/model/createTable/.svn/text-base/TableModel.java.svn-base @@ -0,0 +1,44 @@ +package cn.tootoo.base.template.model.createTable; + +import java.util.List; + +public class TableModel { + private String tableName; + private String tablePk; + private String tableRemarks; + private List columnlist; + + public String getTablePk() { + return tablePk; + } + + + public void setTablePk(String tablePk) { + this.tablePk = tablePk; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public List getColumnlist() { + return columnlist; + } + + public void setColumnlist(List columnlist) { + this.columnlist = columnlist; + } + + public String getTableRemarks() { + return tableRemarks; + } + + public void setTableRemarks(String tableRemarks) { + this.tableRemarks = tableRemarks; + } + +} diff --git a/src/com/taover/base/template/model/createTable/ColumnModel.java b/src/com/taover/base/template/model/createTable/ColumnModel.java new file mode 100644 index 0000000..65e3db2 --- /dev/null +++ b/src/com/taover/base/template/model/createTable/ColumnModel.java @@ -0,0 +1,64 @@ +package com.taover.base.template.model.createTable; + +public class ColumnModel { + private String columnName; + private boolean nullable; + private String columnSQLType; + private String columnRemarks; + private String columnSize; + private String columnDefaults; + + public String getColumnName() { + return columnName; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public boolean isNullable() { + return nullable; + } + + public void setNullable(boolean nullable) { + this.nullable = nullable; + } + + public String getColumnSQLType() { + return columnSQLType; + } + + public void setColumnSQLType(String columnSQLType) { + this.columnSQLType = columnSQLType; + } + + public String getColumnRemarks() { + return columnRemarks; + } + + public void setColumnRemarks(String columnRemarks) { + this.columnRemarks = columnRemarks; + } + + + public String getColumnSize() { + return columnSize; + } + + + public void setColumnSize(String columnSize) { + this.columnSize = columnSize; + } + + + public String getColumnDefaults() { + return columnDefaults; + } + + + public void setColumnDefaults(String columnDefaults) { + this.columnDefaults = columnDefaults; + } + + +} diff --git a/src/com/taover/base/template/model/createTable/TableModel.java b/src/com/taover/base/template/model/createTable/TableModel.java new file mode 100644 index 0000000..401a456 --- /dev/null +++ b/src/com/taover/base/template/model/createTable/TableModel.java @@ -0,0 +1,44 @@ +package com.taover.base.template.model.createTable; + +import java.util.List; + +public class TableModel { + private String tableName; + private String tablePk; + private String tableRemarks; + private List columnlist; + + public String getTablePk() { + return tablePk; + } + + + public void setTablePk(String tablePk) { + this.tablePk = tablePk; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public List getColumnlist() { + return columnlist; + } + + public void setColumnlist(List columnlist) { + this.columnlist = columnlist; + } + + public String getTableRemarks() { + return tableRemarks; + } + + public void setTableRemarks(String tableRemarks) { + this.tableRemarks = tableRemarks; + } + +} diff --git a/src/com/taover/base/template/model/dao/.svn/entries b/src/com/taover/base/template/model/dao/.svn/entries new file mode 100644 index 0000000..f48ec9f --- /dev/null +++ b/src/com/taover/base/template/model/dao/.svn/entries @@ -0,0 +1,130 @@ +10 + +dir +115305 +svn://119.254.17.138/repos/%E6%B2%B1%E6%B2%B1%E7%94%9F%E6%B4%BB%E7%BD%91%E8%B6%85/code/soa.tootoo.cn/trunk/generate-tootoo-dao-po/src/cn/tootoo/base/template/model/dao +svn://119.254.17.138/repos + + + +2014-06-03T00:22:16.481511Z +63469 +wangpeng + + +svn:special svn:externals svn:needs-lock + + + + + + + + + + + +5351f05e-98f4-42cc-8e6a-33022518c94f + +BaseModel.java +file + + + + +2015-08-10T05:52:55.691000Z +552925e9c99237e6be4d450a84414d90 +2014-05-23T03:31:02.661296Z +62995 +wangpeng + + + + + + + + + + + + + + + + + + + + + +1065 + +DaoModel.java +file + + + + +2015-08-10T05:52:55.645000Z +d34ac2635066f47214bb37fd65b6ec3c +2014-06-03T00:22:16.481511Z +63469 +wangpeng + + + + + + + + + + + + + + + + + + + + + +3009 + +FunctionModel.java +file + + + + +2015-08-10T05:52:55.667000Z +5acc3b6225a53209ab1fef0825622349 +2014-05-21T02:30:56.456467Z +62786 +wangpeng + + + + + + + + + + + + + + + + + + + + + +2233 + diff --git a/src/com/taover/base/template/model/dao/.svn/text-base/BaseModel.java.svn-base b/src/com/taover/base/template/model/dao/.svn/text-base/BaseModel.java.svn-base new file mode 100644 index 0000000..1966b85 --- /dev/null +++ b/src/com/taover/base/template/model/dao/.svn/text-base/BaseModel.java.svn-base @@ -0,0 +1,40 @@ +package cn.tootoo.base.template.model.dao; + +public class BaseModel { + private String beanVarName; + private String function_return; + private String function_name; + private String function_param; + private String function_body; + + public String getBeanVarName() { + return beanVarName; + } + public void setBeanVarName(String beanVarName) { + this.beanVarName = beanVarName; + } + public String getFunction_return() { + return function_return; + } + public void setFunction_return(String function_return) { + this.function_return = function_return; + } + public String getFunction_name() { + return function_name; + } + public void setFunction_name(String function_name) { + this.function_name = function_name; + } + public String getFunction_param() { + return function_param; + } + public void setFunction_param(String function_param) { + this.function_param = function_param; + } + public String getFunction_body() { + return function_body; + } + public void setFunction_body(String function_body) { + this.function_body = function_body; + } +} diff --git a/src/com/taover/base/template/model/dao/.svn/text-base/DaoModel.java.svn-base b/src/com/taover/base/template/model/dao/.svn/text-base/DaoModel.java.svn-base new file mode 100644 index 0000000..9305d14 --- /dev/null +++ b/src/com/taover/base/template/model/dao/.svn/text-base/DaoModel.java.svn-base @@ -0,0 +1,116 @@ +package cn.tootoo.base.template.model.dao; + +import java.util.List; +import java.util.Map; + +import cn.tootoo.base.template.model.po.ColumnModel; + +public class DaoModel { + + private String users; + private String version; + private String packages; + private String beanName; + private String tableName; + private List imports; + private List propertys; + private List funlist; + private Map reqParameterToPOMap; + private List columnList; + private String pkBeanName; + private String pkColumName; + private String pkType; + private String column_list_str; + private String dbType; + + public String getColumn_list_str() { + return column_list_str; + } + public void setColumn_list_str(String column_list_str) { + this.column_list_str = column_list_str; + } + public String getUsers() { + return users; + } + public void setUsers(String users) { + this.users = users; + } + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + public String getPackages() { + return packages; + } + public void setPackages(String packages) { + this.packages = packages; + } + public String getBeanName() { + return beanName; + } + public void setBeanName(String beanName) { + this.beanName = beanName; + } + public String getTableName() { + return tableName; + } + public void setTableName(String tableName) { + this.tableName = tableName; + } + public List getImports() { + return imports; + } + public void setImports(List imports) { + this.imports = imports; + } + public List getPropertys() { + return propertys; + } + public void setPropertys(List propertys) { + this.propertys = propertys; + } + public List getFunlist() { + return funlist; + } + public void setFunlist(List funlist) { + this.funlist = funlist; + } + public Map getReqParameterToPOMap() { + return reqParameterToPOMap; + } + public void setReqParameterToPOMap(Map reqParameterToPOMap) { + this.reqParameterToPOMap = reqParameterToPOMap; + } + public List getColumnList() { + return columnList; + } + public void setColumnList(List columnList) { + this.columnList = columnList; + } + public String getPkBeanName() { + return pkBeanName; + } + public void setPkBeanName(String pkBeanName) { + this.pkBeanName = pkBeanName; + } + public String getPkColumName() { + return pkColumName; + } + public void setPkColumName(String pkColumName) { + this.pkColumName = pkColumName; + } + public String getPkType() { + return pkType; + } + public void setPkType(String pK_TYPE) { + pkType = pK_TYPE; + } + public String getDbType() { + return dbType; + } + public void setDbType(String dbType) { + this.dbType = dbType; + } +} diff --git a/src/com/taover/base/template/model/dao/.svn/text-base/FunctionModel.java.svn-base b/src/com/taover/base/template/model/dao/.svn/text-base/FunctionModel.java.svn-base new file mode 100644 index 0000000..4811430 --- /dev/null +++ b/src/com/taover/base/template/model/dao/.svn/text-base/FunctionModel.java.svn-base @@ -0,0 +1,97 @@ +package cn.tootoo.base.template.model.dao; + +import java.util.List; + +public class FunctionModel { + // 方法返回类型 + private String function_return; + // 方法名 + private String function_name; + // 方法参数名称 + private List function_param; + // 形参(类型 名称) + private String function_params; + // 方法抛出异常 + private List function_exception; + // 方法描述 + private String function_description; + // 异常描述 + private String function_exceptions; + // 方法体 + private String function_body; + // 是否是重写方法 + private String over; + + public String getFunction_return() { + return function_return; + } + + public void setFunction_return(String function_return) { + this.function_return = function_return; + } + + public String getFunction_name() { + return function_name; + } + + public void setFunction_name(String function_name) { + this.function_name = function_name; + } + + public List getFunction_param() { + return function_param; + } + + public void setFunction_param(List function_param) { + this.function_param = function_param; + } + + public List getFunction_exception() { + return function_exception; + } + + public void setFunction_exception(List function_exception) { + this.function_exception = function_exception; + } + + public String getFunction_description() { + return function_description; + } + + public void setFunction_description(String function_description) { + this.function_description = function_description; + } + + public String getFunction_params() { + return function_params; + } + + public void setFunction_params(String function_params) { + this.function_params = function_params; + } + + public String getFunction_exceptions() { + return function_exceptions; + } + + public void setFunction_exceptions(String function_exceptions) { + this.function_exceptions = function_exceptions; + } + + public String getFunction_body() { + return function_body; + } + + public void setFunction_body(String function_body) { + this.function_body = function_body; + } + + public String getOver() { + return over; + } + + public void setOver(String over) { + this.over = over; + } + +} diff --git a/src/com/taover/base/template/model/dao/BaseModel.java b/src/com/taover/base/template/model/dao/BaseModel.java new file mode 100644 index 0000000..e952e09 --- /dev/null +++ b/src/com/taover/base/template/model/dao/BaseModel.java @@ -0,0 +1,40 @@ +package com.taover.base.template.model.dao; + +public class BaseModel { + private String beanVarName; + private String function_return; + private String function_name; + private String function_param; + private String function_body; + + public String getBeanVarName() { + return beanVarName; + } + public void setBeanVarName(String beanVarName) { + this.beanVarName = beanVarName; + } + public String getFunction_return() { + return function_return; + } + public void setFunction_return(String function_return) { + this.function_return = function_return; + } + public String getFunction_name() { + return function_name; + } + public void setFunction_name(String function_name) { + this.function_name = function_name; + } + public String getFunction_param() { + return function_param; + } + public void setFunction_param(String function_param) { + this.function_param = function_param; + } + public String getFunction_body() { + return function_body; + } + public void setFunction_body(String function_body) { + this.function_body = function_body; + } +} diff --git a/src/com/taover/base/template/model/dao/DaoModel.java b/src/com/taover/base/template/model/dao/DaoModel.java new file mode 100644 index 0000000..753b944 --- /dev/null +++ b/src/com/taover/base/template/model/dao/DaoModel.java @@ -0,0 +1,117 @@ +package com.taover.base.template.model.dao; + +import java.util.List; +import java.util.Map; + +import com.taover.base.template.model.po.ColumnModel; + + +public class DaoModel { + + private String users; + private String version; + private String packages; + private String beanName; + private String tableName; + private List imports; + private List propertys; + private List funlist; + private Map reqParameterToPOMap; + private List columnList; + private String pkBeanName; + private String pkColumName; + private String pkType; + private String column_list_str; + private String dbType; + + public String getColumn_list_str() { + return column_list_str; + } + public void setColumn_list_str(String column_list_str) { + this.column_list_str = column_list_str; + } + public String getUsers() { + return users; + } + public void setUsers(String users) { + this.users = users; + } + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + public String getPackages() { + return packages; + } + public void setPackages(String packages) { + this.packages = packages; + } + public String getBeanName() { + return beanName; + } + public void setBeanName(String beanName) { + this.beanName = beanName; + } + public String getTableName() { + return tableName; + } + public void setTableName(String tableName) { + this.tableName = tableName; + } + public List getImports() { + return imports; + } + public void setImports(List imports) { + this.imports = imports; + } + public List getPropertys() { + return propertys; + } + public void setPropertys(List propertys) { + this.propertys = propertys; + } + public List getFunlist() { + return funlist; + } + public void setFunlist(List funlist) { + this.funlist = funlist; + } + public Map getReqParameterToPOMap() { + return reqParameterToPOMap; + } + public void setReqParameterToPOMap(Map reqParameterToPOMap) { + this.reqParameterToPOMap = reqParameterToPOMap; + } + public List getColumnList() { + return columnList; + } + public void setColumnList(List columnList) { + this.columnList = columnList; + } + public String getPkBeanName() { + return pkBeanName; + } + public void setPkBeanName(String pkBeanName) { + this.pkBeanName = pkBeanName; + } + public String getPkColumName() { + return pkColumName; + } + public void setPkColumName(String pkColumName) { + this.pkColumName = pkColumName; + } + public String getPkType() { + return pkType; + } + public void setPkType(String pK_TYPE) { + pkType = pK_TYPE; + } + public String getDbType() { + return dbType; + } + public void setDbType(String dbType) { + this.dbType = dbType; + } +} diff --git a/src/com/taover/base/template/model/dao/FunctionModel.java b/src/com/taover/base/template/model/dao/FunctionModel.java new file mode 100644 index 0000000..3d8ec5e --- /dev/null +++ b/src/com/taover/base/template/model/dao/FunctionModel.java @@ -0,0 +1,97 @@ +package com.taover.base.template.model.dao; + +import java.util.List; + +public class FunctionModel { + // 方法返回类型 + private String function_return; + // 方法名 + private String function_name; + // 方法参数名称 + private List function_param; + // 形参(类型 名称) + private String function_params; + // 方法抛出异常 + private List function_exception; + // 方法描述 + private String function_description; + // 异常描述 + private String function_exceptions; + // 方法体 + private String function_body; + // 是否是重写方法 + private String over; + + public String getFunction_return() { + return function_return; + } + + public void setFunction_return(String function_return) { + this.function_return = function_return; + } + + public String getFunction_name() { + return function_name; + } + + public void setFunction_name(String function_name) { + this.function_name = function_name; + } + + public List getFunction_param() { + return function_param; + } + + public void setFunction_param(List function_param) { + this.function_param = function_param; + } + + public List getFunction_exception() { + return function_exception; + } + + public void setFunction_exception(List function_exception) { + this.function_exception = function_exception; + } + + public String getFunction_description() { + return function_description; + } + + public void setFunction_description(String function_description) { + this.function_description = function_description; + } + + public String getFunction_params() { + return function_params; + } + + public void setFunction_params(String function_params) { + this.function_params = function_params; + } + + public String getFunction_exceptions() { + return function_exceptions; + } + + public void setFunction_exceptions(String function_exceptions) { + this.function_exceptions = function_exceptions; + } + + public String getFunction_body() { + return function_body; + } + + public void setFunction_body(String function_body) { + this.function_body = function_body; + } + + public String getOver() { + return over; + } + + public void setOver(String over) { + this.over = over; + } + +} diff --git a/src/com/taover/base/template/model/po/.svn/entries b/src/com/taover/base/template/model/po/.svn/entries new file mode 100644 index 0000000..074b04d --- /dev/null +++ b/src/com/taover/base/template/model/po/.svn/entries @@ -0,0 +1,130 @@ +10 + +dir +115305 +svn://119.254.17.138/repos/%E6%B2%B1%E6%B2%B1%E7%94%9F%E6%B4%BB%E7%BD%91%E8%B6%85/code/soa.tootoo.cn/trunk/generate-tootoo-dao-po/src/cn/tootoo/base/template/model/po +svn://119.254.17.138/repos + + + +2014-05-21T06:48:36.887728Z +62846 +wangpeng + + +svn:special svn:externals svn:needs-lock + + + + + + + + + + + +5351f05e-98f4-42cc-8e6a-33022518c94f + +ColumnModel.java +file + + + + +2015-08-10T05:52:55.898000Z +b20b551adbb9cf3a5207c168b856d332 +2014-05-21T06:48:36.887728Z +62846 +wangpeng + + + + + + + + + + + + + + + + + + + + + +1507 + +PoModel.java +file + + + + +2015-08-10T05:52:55.839000Z +bdbc3709b8452e308f72e6b71c4cc9e2 +2014-05-21T03:24:19.464571Z +62806 +wangpeng + + + + + + + + + + + + + + + + + + + + + +1144 + +TableModel.java +file + + + + +2015-08-10T05:52:55.872000Z +b95c5663c4c68cf2b4d568d8e43018cd +2014-05-21T03:24:19.464571Z +62806 +wangpeng + + + + + + + + + + + + + + + + + + + + + +487 + diff --git a/src/com/taover/base/template/model/po/.svn/text-base/ColumnModel.java.svn-base b/src/com/taover/base/template/model/po/.svn/text-base/ColumnModel.java.svn-base new file mode 100644 index 0000000..1acb211 --- /dev/null +++ b/src/com/taover/base/template/model/po/.svn/text-base/ColumnModel.java.svn-base @@ -0,0 +1,73 @@ +package cn.tootoo.base.template.model.po; + +public class ColumnModel { + private String columnName; + private String columnMethodName; + private String columnUName; + public String getColumnUName() { + return columnUName; + } + + public void setColumnUName(String columnUName) { + this.columnUName = columnUName; + } + + private int columnSQLType; + private String columnJAVAType; + private String columnRemarks; + private String seqName; + private int column_Scale; + + public String getColumnName() { + return columnName; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public String getColumnMethodName() { + return columnMethodName; + } + + public void setColumnMethodName(String columnMethodName) { + this.columnMethodName = columnMethodName; + } + + public int getColumnSQLType() { + return columnSQLType; + } + + public String getColumnJAVAType() { + return columnJAVAType; + } + + public void setColumnJAVAType(String columnJAVAType) { + this.columnJAVAType = columnJAVAType; + } + + public String getColumnRemarks() { + return columnRemarks; + } + + public void setColumnRemarks(String columnRemarks) { + this.columnRemarks = columnRemarks; + } + + public int getColumn_Scale() { + return column_Scale; + } + + public void setColumn_Scale(int column_Scale) { + this.column_Scale = column_Scale; + } + + public String getSeqName() { + return seqName; + } + + public void setSeqName(String seqName) { + this.seqName = seqName; + } + +} diff --git a/src/com/taover/base/template/model/po/.svn/text-base/PoModel.java.svn-base b/src/com/taover/base/template/model/po/.svn/text-base/PoModel.java.svn-base new file mode 100644 index 0000000..c258671 --- /dev/null +++ b/src/com/taover/base/template/model/po/.svn/text-base/PoModel.java.svn-base @@ -0,0 +1,64 @@ +package cn.tootoo.base.template.model.po; + + +public class PoModel { + // 包名 + private String packages; + // 作者 + private String users; + // 版本 + private String version; + + private String name; + private String toStringMethodBody; + private TableModel tablemodel; + + public String getPackages() { + return packages; + } + + public void setPackages(String packages) { + this.packages = packages; + } + + public String getUsers() { + return users; + } + + public void setUsers(String users) { + this.users = users; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public TableModel getTablemodel() { + return tablemodel; + } + + public void setTablemodel(TableModel tablemodel) { + this.tablemodel = tablemodel; + } + + public String getToStringMethodBody() { + return toStringMethodBody; + } + + public void setToStringMethodBody(String toStringMethodBody) { + this.toStringMethodBody = toStringMethodBody; + } + +} diff --git a/src/com/taover/base/template/model/po/.svn/text-base/TableModel.java.svn-base b/src/com/taover/base/template/model/po/.svn/text-base/TableModel.java.svn-base new file mode 100644 index 0000000..d4c2143 --- /dev/null +++ b/src/com/taover/base/template/model/po/.svn/text-base/TableModel.java.svn-base @@ -0,0 +1,25 @@ +package cn.tootoo.base.template.model.po; + +import java.util.List; + +public class TableModel { + private String tableName; + private List columnlist; + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public List getColumnlist() { + return columnlist; + } + + public void setColumnlist(List columnlist) { + this.columnlist = columnlist; + } + +} diff --git a/src/com/taover/base/template/model/po/ColumnModel.java b/src/com/taover/base/template/model/po/ColumnModel.java new file mode 100644 index 0000000..79cc624 --- /dev/null +++ b/src/com/taover/base/template/model/po/ColumnModel.java @@ -0,0 +1,73 @@ +package com.taover.base.template.model.po; + +public class ColumnModel { + private String columnName; + private String columnMethodName; + private String columnUName; + public String getColumnUName() { + return columnUName; + } + + public void setColumnUName(String columnUName) { + this.columnUName = columnUName; + } + + private int columnSQLType; + private String columnJAVAType; + private String columnRemarks; + private String seqName; + private int column_Scale; + + public String getColumnName() { + return columnName; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public String getColumnMethodName() { + return columnMethodName; + } + + public void setColumnMethodName(String columnMethodName) { + this.columnMethodName = columnMethodName; + } + + public int getColumnSQLType() { + return columnSQLType; + } + + public String getColumnJAVAType() { + return columnJAVAType; + } + + public void setColumnJAVAType(String columnJAVAType) { + this.columnJAVAType = columnJAVAType; + } + + public String getColumnRemarks() { + return columnRemarks; + } + + public void setColumnRemarks(String columnRemarks) { + this.columnRemarks = columnRemarks; + } + + public int getColumn_Scale() { + return column_Scale; + } + + public void setColumn_Scale(int column_Scale) { + this.column_Scale = column_Scale; + } + + public String getSeqName() { + return seqName; + } + + public void setSeqName(String seqName) { + this.seqName = seqName; + } + +} diff --git a/src/com/taover/base/template/model/po/PoModel.java b/src/com/taover/base/template/model/po/PoModel.java new file mode 100644 index 0000000..fa78f2c --- /dev/null +++ b/src/com/taover/base/template/model/po/PoModel.java @@ -0,0 +1,64 @@ +package com.taover.base.template.model.po; + + +public class PoModel { + // 包名 + private String packages; + // 作者 + private String users; + // 版本 + private String version; + + private String name; + private String toStringMethodBody; + private TableModel tablemodel; + + public String getPackages() { + return packages; + } + + public void setPackages(String packages) { + this.packages = packages; + } + + public String getUsers() { + return users; + } + + public void setUsers(String users) { + this.users = users; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public TableModel getTablemodel() { + return tablemodel; + } + + public void setTablemodel(TableModel tablemodel) { + this.tablemodel = tablemodel; + } + + public String getToStringMethodBody() { + return toStringMethodBody; + } + + public void setToStringMethodBody(String toStringMethodBody) { + this.toStringMethodBody = toStringMethodBody; + } + +} diff --git a/src/com/taover/base/template/model/po/TableModel.java b/src/com/taover/base/template/model/po/TableModel.java new file mode 100644 index 0000000..1cd7648 --- /dev/null +++ b/src/com/taover/base/template/model/po/TableModel.java @@ -0,0 +1,25 @@ +package com.taover.base.template.model.po; + +import java.util.List; + +public class TableModel { + private String tableName; + private List columnlist; + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public List getColumnlist() { + return columnlist; + } + + public void setColumnlist(List columnlist) { + this.columnlist = columnlist; + } + +} diff --git a/src/com/taover/business/Constants.java b/src/com/taover/business/Constants.java new file mode 100644 index 0000000..c3598f5 --- /dev/null +++ b/src/com/taover/business/Constants.java @@ -0,0 +1,14 @@ +package com.taover.business; + +public class Constants { + public static String TEMPATE_PATH = "/com/taover/base/template/"; + public static String TEMPATE_CONTROLLERNAME = "ControllerTemplate.ftl"; + public static String TEMPATE_CONTROLLER_EXPORT_NAME = "ControllerExportTemplate.ftl"; + public static String TEMPATE_SERVICEIMPLNAME = "ServiceImplTemplate.ftl"; + public static String TEMPATE_SERVICENAME = "ServiceTemplate.ftl"; + public static String TEMPATE_EXPORT_SERVICENAME = "ServiceExportTemplate.ftl"; + public static String TEMPATE_HTMLNAME = "HtmlTemplate.ftl"; + public static String TEMPATE_HTMLLAYUINAME = "HtmlLayuiTemplate.ftl"; + public static String TEMPATE_JSNAME = "JsTemplate.ftl"; +} + diff --git a/src/com/taover/business/GenerateCS.java b/src/com/taover/business/GenerateCS.java new file mode 100644 index 0000000..6b4c3ab --- /dev/null +++ b/src/com/taover/business/GenerateCS.java @@ -0,0 +1,96 @@ +package com.taover.business; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.Vector; + +import com.taover.base.template.model.bussiness.EnvironmentModel; +import com.taover.db.TableColumn; +import com.taover.db.Tools; +import com.taover.tools.StringUtil; + +public class GenerateCS { + + public static void main(String[] args) throws Exception{ + //读取配置文件 + Properties properties = Tools.getProperties(); + //取数据库连接 + Connection conn = Tools.getConnection(properties); + //初始化要生成的表列表 + List tableNameList = new ArrayList(); + + String schameName = properties.getProperty("SchameName"); + String createSchame = properties.getProperty("CreateSchame"); + String dbType = properties.getProperty("dbtype"); + String tableName = properties.getProperty("TableName"); + if("mysql".equalsIgnoreCase(dbType)){ + //schameName = schameName.toUpperCase(); + } + + if (createSchame.equalsIgnoreCase("true") || "ALL".equalsIgnoreCase(tableName) ) { + + String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '"+schameName+"'"; + ResultSet rs = Tools.executeQuery(Tools.createStmt(conn), sql); + if (null == rs) + return ; + try { + while (rs.next()) { + tableNameList.add(rs.getString("Table_name")); + } + } catch (SQLException e) { + e.printStackTrace(); + } + Tools.close(rs); + } else { + if("mysql".equalsIgnoreCase(dbType)){ + tableName = tableName.toUpperCase(); + } + String[] TableNameArr = tableName.split(","); + for (int i = 0; i < TableNameArr.length; i++) + tableNameList.add(TableNameArr[i]); + + } + + //读取配置文件信息 + String modulePackageInfo = properties.getProperty("modulePackageInfo"); + String moduleFilePath = properties.getProperty("moduleFilePath"); + String dbPackageInfo = properties.getProperty("dbPackageInfo"); + String dbLikeStr = properties.getProperty("DBLikeStr"); + + //循环遍历各个表名 + for (int i = 0; i < tableNameList.size(); i++) { + String tableNameCurr = (String) tableNameList.get(i); + + // 取得表中所有列 + Vector columnsInTable = TableColumn.GetTableInfo(conn, schameName, tableNameCurr, dbLikeStr, dbType); + if (columnsInTable == null || columnsInTable.size() == 0) { + System.out.println(tableNameCurr + " : 生成失败,得不到表中列明"); + continue; + } + TableColumn pkcolum = TableColumn.getPKColum(columnsInTable); + if (pkcolum == null) { + System.out.println(tableNameCurr + " : 生成失败,未设置主键"); + continue; + } + + String beanClassName = StringUtil.formatBeanNameFirstUpper(tableNameCurr); + String poPackageInfo = dbPackageInfo + "." + beanClassName.toLowerCase(); + + String moduleName = tableNameCurr.split("_")[0]; + EnvironmentModel envir = EnvironmentModel.createEnvironmentModel(modulePackageInfo, moduleFilePath, poPackageInfo, beanClassName, moduleName); + //生成Controller层 + GenerateController.generateController(envir, false, columnsInTable); + //生成Service层 + GenerateService.generateService(envir, false); + + System.out.println(tableNameCurr + " : 生成结束"); + } + conn.close(); + System.out.println("全部结束"); + + } +} diff --git a/src/com/taover/business/GenerateController.java b/src/com/taover/business/GenerateController.java new file mode 100644 index 0000000..d7ca7b0 --- /dev/null +++ b/src/com/taover/business/GenerateController.java @@ -0,0 +1,48 @@ +package com.taover.business; + +import java.io.File; +import java.io.StringWriter; +import java.util.Vector; + +import com.taover.base.template.model.bussiness.ControllerModel; +import com.taover.base.template.model.bussiness.EnvironmentModel; +import com.taover.db.TableColumn; +import com.taover.db.Tools; + +import freemarker.template.Configuration; +import freemarker.template.Template; + +public class GenerateController { + + public static void generateController(EnvironmentModel enirModel, boolean coverWhenFileExists, Vector columnsInTable) { + try{ + ControllerModel model = ControllerModel.createControllerModel( + enirModel.getControllerPackageInfo(), + enirModel.getPoPackageInfo(), + enirModel.getServicePackageInfo(), + enirModel.getBeanClassName(), + enirModel.getMainPackageInfo(), + enirModel.getSubModuleName(), + columnsInTable); + + File f = new File(Tools.getPath() + Constants.TEMPATE_PATH); + Configuration cfg = new Configuration(); + cfg.setDirectoryForTemplateLoading(f); + + StringWriter out = new StringWriter(); + Template template = cfg.getTemplate(Constants.TEMPATE_CONTROLLERNAME, "UTF-8"); + template.process(model, out); + + String destFilePath = enirModel.getControllerFilePath() + File.separator + model.getControllerClassName() + ".java"; + File destFile = new File(destFilePath); + if(coverWhenFileExists || !destFile.exists()){ + Tools.createFile(enirModel.getControllerFilePath(), model.getControllerClassName()+".java", out.toString()); + }else{ + System.out.println("文件生成:"+destFile.getName()+"文件已经存在,未覆盖!"); + } + + }catch(Exception e){ + e.printStackTrace(); + } + } +} diff --git a/src/com/taover/business/GenerateService.java b/src/com/taover/business/GenerateService.java new file mode 100644 index 0000000..b261f3e --- /dev/null +++ b/src/com/taover/business/GenerateService.java @@ -0,0 +1,57 @@ +package com.taover.business; + +import java.io.File; +import java.io.StringWriter; + +import com.taover.base.template.model.bussiness.EnvironmentModel; +import com.taover.base.template.model.bussiness.ServiceModel; +import com.taover.db.Tools; + +import freemarker.template.Configuration; +import freemarker.template.Template; + +public class GenerateService { + + public static void generateService(EnvironmentModel enirModel, boolean coverWhenFileExists) { + try{ + ServiceModel model = ServiceModel.createServiceModel( + enirModel.getPoPackageInfo(), + enirModel.getBeanClassName(), + enirModel.getMainPackageInfo(), + enirModel.getSubModuleName()); + + File f = new File(Tools.getPath() + Constants.TEMPATE_PATH); + Configuration cfg = new Configuration(); + cfg.setDirectoryForTemplateLoading(f); + + //service实现文件 + StringWriter outService = new StringWriter(); + Template templateService = cfg.getTemplate(Constants.TEMPATE_SERVICEIMPLNAME, "UTF-8"); + templateService.process(model, outService); + File destFile = new File( + enirModel.getServiceFilePath()+File.separator+ + "impl"+File.separator+ + model.getBeanClassName()+"ServiceImpl.java"); + if(coverWhenFileExists || !destFile.exists()){ + Tools.createFile(enirModel.getServiceFilePath()+File.separator+"impl", model.getBeanClassName()+"ServiceImpl.java", outService.toString()); + }else{ + System.out.println("文件生成:"+destFile.getName()+"文件已经存在,未覆盖!"); + } + + //service接口文件 + StringWriter outServiceImpl = new StringWriter(); + Template templateServiceImpl = cfg.getTemplate(Constants.TEMPATE_SERVICENAME, "UTF-8"); + templateServiceImpl.process(model, outServiceImpl); + File destFile2 = new File( + enirModel.getServiceFilePath()+File.separator+ + model.getBeanClassName()+"Service.java"); + if(coverWhenFileExists || !destFile2.exists()){ + Tools.createFile(enirModel.getServiceFilePath(), model.getBeanClassName()+"Service.java", outServiceImpl.toString()); + }else{ + System.out.println("文件生成:"+destFile2.getName()+"文件已经存在,未覆盖!"); + } + }catch(Exception e){ + e.printStackTrace(); + } + } +} diff --git a/src/com/taover/business/GenerateVCSDP.java b/src/com/taover/business/GenerateVCSDP.java new file mode 100644 index 0000000..d51fb49 --- /dev/null +++ b/src/com/taover/business/GenerateVCSDP.java @@ -0,0 +1,128 @@ +package com.taover.business; + +import java.io.File; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.Vector; + +import com.taover.base.template.model.bussiness.EnvironmentModel; +import com.taover.db.GenerateDao; +import com.taover.db.GeneratePO; +import com.taover.db.TableColumn; +import com.taover.db.Tools; +import com.taover.tools.StringUtil; + +public class GenerateVCSDP { + + public static void main(String[] args) { + try { + generate(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public static void generate() throws Exception{ + //读取配置文件 + Properties properties = Tools.getProperties(); + //取数据库连接 + Connection conn = Tools.getConnection(properties); + //初始化要生成的表列表 + List tableNameList = new ArrayList(); + + //读取基本信息 + String outputPath = properties.getProperty("OutputPath"); + String schameName = properties.getProperty("SchameName"); + String dbLikeStr = properties.getProperty("DBLikeStr"); + String dbType = properties.getProperty("dbtype"); + String dbPackagePath = properties.getProperty("packageName"); + String tableName = properties.getProperty("TableName"); + + //读取配置文件信息-Controller、Service层需要 + String modulePackageInfo = properties.getProperty("modulePackageInfo"); + String moduleFilePath = properties.getProperty("moduleFilePath"); + String dbPackageInfo = properties.getProperty("dbPackageInfo"); + + //如果文件已存在是否覆盖 + boolean coverWhenFileExists = false; + if(properties.getProperty("coverWhenFileExists") != null){ + coverWhenFileExists = Boolean.valueOf(properties.getProperty("coverWhenFileExists")); + } + + //读取配置文件信息-HTML、JS需要 + String webRootPath = properties.getProperty("WebRootPath"); + + if("mysql".equalsIgnoreCase(dbType)){ + schameName = schameName.toUpperCase(); + } + + if (!dbPackagePath.substring(dbPackagePath.length()-1).equals(".")) + dbPackagePath += "."; + + if ("ALL".equalsIgnoreCase(tableName) ) { + + String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '"+schameName+"'"; + ResultSet rs = Tools.executeQuery(Tools.createStmt(conn), sql); + if (null == rs) + return ; + try { + while (rs.next()) { + tableNameList.add(rs.getString("Table_name")); + } + } catch (SQLException e) { + e.printStackTrace(); + } + Tools.close(rs); + } else { + if("mysql".equalsIgnoreCase(dbType)){ +// tableName = tableName.toUpperCase(); + } + String[] TableNameArr = tableName.split(","); + for (int i = 0; i < TableNameArr.length; i++) + tableNameList.add(TableNameArr[i]); + } + + for (int i = 0; i < tableNameList.size(); i++) { + + String tableNameCurr = (String) tableNameList.get(i); + + // 取得表中所有列 + Vector columnsInTable = TableColumn.GetTableInfo(conn, schameName, tableNameCurr, dbLikeStr, dbType); + if (columnsInTable == null || columnsInTable.size() == 0) { + System.out.println(tableNameCurr + " : 生成失败,得不到表中列明"); + continue; + } + TableColumn pkcolum = TableColumn.getPKColum(columnsInTable); + if (pkcolum == null) { + System.out.println(tableNameCurr + " : 生成失败,未设置主键"); + continue; + } + + // 生成po类 + GeneratePO.generatePO(outputPath, dbPackagePath, columnsInTable); + // 生成Dao + GenerateDao.table2dao(outputPath, dbPackagePath, columnsInTable, dbType); + + String beanClassName = StringUtil.formatBeanNameFirstUpper(tableNameCurr); + String poPackageInfo = dbPackageInfo + "." + beanClassName.toLowerCase(); + + String moduleName = tableNameCurr.split("_")[0]; + EnvironmentModel envir = EnvironmentModel.createEnvironmentModel(modulePackageInfo, moduleFilePath, poPackageInfo, beanClassName, moduleName); + //生成Controller层 + GenerateController.generateController(envir, coverWhenFileExists, columnsInTable); + //生成Service层 + GenerateService.generateService(envir, coverWhenFileExists); + //生成view + GenerateView.generateView(webRootPath, tableNameCurr, columnsInTable, coverWhenFileExists); + + System.out.println(tableNameCurr + " : 生成结束"); + } + conn.close(); + System.out.println("全部结束"); + } +} diff --git a/src/com/taover/business/GenerateView.java b/src/com/taover/business/GenerateView.java new file mode 100644 index 0000000..7952721 --- /dev/null +++ b/src/com/taover/business/GenerateView.java @@ -0,0 +1,140 @@ +package com.taover.business; + +import java.io.File; +import java.io.StringWriter; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.Vector; + +import com.taover.base.template.model.bussiness.ViewModel; +import com.taover.db.TableColumn; +import com.taover.db.Tools; +import com.taover.tools.StringUtil; + +import freemarker.template.Configuration; +import freemarker.template.Template; + +public class GenerateView { + public static void main(String args[]) throws SQLException{ + //读取配置文件 + Properties properties = Tools.getProperties(); + //取数据库连接 + Connection conn = Tools.getConnection(properties); + //初始化要生成的表列表 + List tableNameList = new ArrayList(); + + String outputPath = properties.getProperty("OutputPath"); + String schameName = properties.getProperty("SchameName"); + String createSchame = properties.getProperty("CreateSchame"); + String dbLikeStr = properties.getProperty("DBLikeStr"); + String dbType = properties.getProperty("dbtype"); + String dbPackagePath = properties.getProperty("packageName"); + String tableName = properties.getProperty("TableName"); + + //WebRootPath读取 + String webRootPath = properties.getProperty("WebRootPath"); + + if("mysql".equalsIgnoreCase(dbType)){ + //schameName = schameName.toUpperCase(); + } + + if ("ALL".equalsIgnoreCase(tableName) ) { + + String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '"+schameName+"'"; + ResultSet rs = Tools.executeQuery(Tools.createStmt(conn), sql); + if (null == rs) + return ; + List result = new ArrayList(); + try { + while (rs.next()) { + tableNameList.add(rs.getString("Table_name")); + } + } catch (SQLException e) { + e.printStackTrace(); + result = null; + } + Tools.close(rs); + } else { + if("mysql".equalsIgnoreCase(dbType)){ + tableName = tableName.toUpperCase(); + } + String[] TableNameArr = tableName.split(","); + for (int i = 0; i < TableNameArr.length; i++) + tableNameList.add(TableNameArr[i]); + + } + + for (int i = 0; i < tableNameList.size(); i++) { + String tableNameCurr = (String) tableNameList.get(i); + + // 取得表中所有列 + Vector columnsInTable = TableColumn.GetTableInfo(conn, schameName, tableNameCurr, dbLikeStr, dbType); + if (columnsInTable == null || columnsInTable.size() == 0) { + System.out.println(tableNameCurr + " : 生成失败,得不到表中列明"); + continue; + } + TableColumn pkcolum = TableColumn.getPKColum(columnsInTable); + if (pkcolum == null) { + System.out.println(tableNameCurr + " : 生成失败,未设置主键"); + continue; + } + + //生成view + generateView(webRootPath, tableNameCurr, columnsInTable, false); + + System.out.println(tableNameCurr + " : 生成结束"); + } + conn.close(); + System.out.println("全部结束"); + } + + public static void generateView(String webRootPath, String tableName, Vector columnsInTable, boolean coverWhenFileExists) { + try{ + String controllerMapping = StringUtil.formatBeanNameFirstLow(tableName).toLowerCase(); + ViewModel model = ViewModel.createViewModel(controllerMapping, webRootPath, columnsInTable); + + File f = new File(Tools.getPath() + Constants.TEMPATE_PATH); + Configuration cfg = new Configuration(); + cfg.setDirectoryForTemplateLoading(f); + + StringWriter htmlOut = new StringWriter(); + Template htmlTemplate = cfg.getTemplate(Constants.TEMPATE_HTMLNAME, "UTF-8"); + htmlTemplate.process(model, htmlOut); + File destFile = new File( + webRootPath+File.separator+"manage"+File.separator+"html"+File.separator+controllerMapping+".html"); + if(coverWhenFileExists || !destFile.exists()){ + Tools.createFile(webRootPath+File.separator+"manage"+File.separator+"html", controllerMapping+".html", htmlOut.toString()); + }else{ + System.out.println("文件生成:"+destFile.getName()+"文件已经存在,未覆盖!"); + } + + StringWriter jsOut = new StringWriter(); + Template jsTemplate = cfg.getTemplate(Constants.TEMPATE_JSNAME, "UTF-8"); + jsTemplate.process(model, jsOut); + File destFile2 = new File( + webRootPath+File.separator+"manage"+File.separator+"js"+File.separator+controllerMapping+".js"); + if(coverWhenFileExists || !destFile2.exists()){ + Tools.createFile(webRootPath+File.separator+"manage"+File.separator+"js", controllerMapping+".js", jsOut.toString()); + }else{ + System.out.println("文件生成:"+destFile2.getName()+"文件已经存在,未覆盖!"); + } + + StringWriter htmlLayuiOut = new StringWriter(); + Template htmlLayuiTemplate = cfg.getTemplate(Constants.TEMPATE_HTMLLAYUINAME, "UTF-8"); + htmlLayuiTemplate.process(model, htmlLayuiOut); + File destLayuiFile = new File( + webRootPath+File.separator+"views"+File.separator+controllerMapping+".html"); + if(coverWhenFileExists || !destLayuiFile.exists()){ + Tools.createFile(webRootPath+File.separator+"views", controllerMapping+".html", htmlLayuiOut.toString()); + }else{ + System.out.println("文件生成:"+destFile.getName()+"文件已经存在,未覆盖!"); + } + }catch(Exception e){ + e.printStackTrace(); + } + } +} diff --git a/src/com/taover/business/Utils.java b/src/com/taover/business/Utils.java new file mode 100644 index 0000000..ffcc7f7 --- /dev/null +++ b/src/com/taover/business/Utils.java @@ -0,0 +1,13 @@ +package com.taover.business; + +public class Utils { + public static String getFirstLetterLower(String source){ + String lowerFirstLetter = ""; + if(source.length() > 0){ + lowerFirstLetter = source.substring(0, 1).toLowerCase(); + }else{ + return ""; + } + return lowerFirstLetter+source.substring(1); + } +} diff --git a/src/com/taover/business/util/TempVelocity.java b/src/com/taover/business/util/TempVelocity.java new file mode 100644 index 0000000..bc17d90 --- /dev/null +++ b/src/com/taover/business/util/TempVelocity.java @@ -0,0 +1,134 @@ +package com.taover.business.util; + +import java.io.File; +import java.io.StringWriter; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.taover.business.Constants; +import com.taover.db.Tools; + +import freemarker.template.Configuration; +import freemarker.template.Template; + +public class TempVelocity { + public static void main(String args[]) throws SQLException{ + String cnFunc = "代销平台毛利=1-代销平台成本/代销平台报价"; +// String func = "promotProfit=promotPrice-promotAllCost-shareReward*shareRewardRate/100"; + generate(cnFunc); + } + + public static void generate(String cnFunc) { + try{ + File f = new File(Tools.getPath() + Constants.TEMPATE_PATH); + Configuration cfg = new Configuration(); + cfg.setDirectoryForTemplateLoading(f); + + StringWriter htmlOut = new StringWriter(); + Template htmlTemplate = cfg.getTemplate("Temp.ftl", "UTF-8"); + Map data = new HashMap(); + data.put("cnFunc", cnFunc); + parseData(data); + + htmlTemplate.process(data, htmlOut); + System.out.println(htmlOut.toString()); + htmlOut.close(); + }catch(Exception e){ + e.printStackTrace(); + } + } + + public static void parseData(Map data){ + //propertyList,result + String cnFunc = (String) data.get("cnFunc"); + + + String result = cnFunc.split("=")[0]; + String resultEn = getEnName(result); + + String propertyStr = cnFunc.split("=")[1]; + List propertyList = new ArrayList(); +// Pattern pattern = Pattern.compile("[a-zA-Z]+", Pattern.CASE_INSENSITIVE); + Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]+", Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(propertyStr); + List cnNameList = new ArrayList(); + String enFunc = cnFunc; + while(matcher.find()){ + String tempGroup = matcher.group(); + cnNameList.add(tempGroup); + } + for(String cnName : cnNameList){ + String enName = getEnName(cnName); + if(enName == null){ + enName = "errorVal"; + } + propertyList.add(enName); + enFunc = enFunc.replaceAll(cnName+"\\b", enName); + } + enFunc = enFunc.replaceAll(result, resultEn); + + data.put("enFunc", enFunc); + data.put("result", resultEn); + data.put("propertyList", propertyList); + } + + public static String getEnName(String cnName){ + Map keyReflect = new HashMap(); + keyReflect.put("供货价格","goodsMoney"); + keyReflect.put("物料成本","materielFee"); + keyReflect.put("运费","freight"); + keyReflect.put("赠品成本","freeGift"); + keyReflect.put("检测成本","detectPer"); + keyReflect.put("预计件数","preNumber"); + keyReflect.put("产品成本","productCost"); + keyReflect.put("分享金","shareReward"); + keyReflect.put("平台售价","platPrice"); + keyReflect.put("平台优惠券","platCoupon"); + keyReflect.put("平台销售成本","platSaleCost"); + keyReflect.put("平台总成本","platAllCost"); + keyReflect.put("平台毛利","platProfit"); + keyReflect.put("平台毛利率","platProfitRate"); + keyReflect.put("初级分享师返利","primaryShareReward"); + keyReflect.put("高级分享师返利","seniorShareReward"); + keyReflect.put("分享后平台最低毛利率","afterSharePlatLowestProfit"); + keyReflect.put("促销价格","promotPrice"); + keyReflect.put("促销产品成本","promotCost"); + keyReflect.put("促销优惠券","promotCoupon"); + keyReflect.put("促销总成本","promotAllCost"); + keyReflect.put("促销毛利","promotProfit"); + keyReflect.put("促销毛利率","promotProfitRate"); + keyReflect.put("促销初级分享师返利","promotPrimaryShareReward"); + keyReflect.put("促销高级分享师返利","promotSeniorShareReward"); + keyReflect.put("促销分享后平台最低毛利","promotAfterShareLowestProfit"); + keyReflect.put("产销联盟报价","psUionPrice"); + keyReflect.put("产销联盟渠道成本","psUnionChannelCost"); + keyReflect.put("联盟毛利率","psUnionProfitRate"); + keyReflect.put("采购渠道报价","channelPrice"); + keyReflect.put("采购渠道成本","purchaseChannelCost"); + keyReflect.put("采购毛利率","purchaseChannelProfitRate"); + keyReflect.put("代销平台报价","agentPrice"); + keyReflect.put("代销平台成本","agentCost"); + keyReflect.put("代销平台毛利","agentProfit"); + keyReflect.put("试吃供货价格","shichiGoodsMoney"); + keyReflect.put("试吃售价","shichiPrice"); + keyReflect.put("试吃份数","shichiNumber"); + keyReflect.put("试吃成本","shichiCost"); + keyReflect.put("试吃利润","shichiProfit"); + keyReflect.put("积分使用率","integralUseRate"); + keyReflect.put("买手提成","ticheng"); + keyReflect.put("运营提点","operateRate"); + keyReflect.put("初级分享师返点","primaryAgentRate"); + keyReflect.put("高级分享师返点","seniorAgentRate"); + keyReflect.put("渠道拓展提点","channelExpRate"); + keyReflect.put("渠道维护提点","channelProRate"); + keyReflect.put("转账费率","transAccountRate"); + keyReflect.put("损耗","lossRate"); + keyReflect.put("分享金比例","shareRewardRate"); + return keyReflect.get(cnName); + } +} diff --git a/src/com/taover/db/Constants.java b/src/com/taover/db/Constants.java new file mode 100644 index 0000000..f4df164 --- /dev/null +++ b/src/com/taover/db/Constants.java @@ -0,0 +1,20 @@ +package com.taover.db; + +public class Constants { + + public static final String LINE = "\r\n"; + public static final String TAB = "\t"; + public static final String NUM_TYPE = "NUMBER"; + public static String[] SCOPES = new String[] { "public", "private", "protected" }; + public static String STATIC = new String("static"); + public static String[] FILE_TYPE = new String[] { "class", "interface" }; + public static String[] SUFFIX = new String[] { "PO", "Dao", "Impl", "DaoImpl" }; + public static String SERIAL = "java.io.Serializable"; + public static String SERIAL_NUM = "private static final long serialVersionUID = 1L;"; + public static String[] KEY_WORD = new String[] { "return", "get", "set", "void", "this." }; + public static String TEMPATE_PATH = "/com/taover/base/template/"; + public static String TEMPATE_DAONAME = "DAOTemplate.ftl"; + public static String TEMPATE_PONAME = "POTemplate.ftl"; + public static String TEMPATE_CREAT_ETABLE_NAME = "createTableTemplate.ftl"; + public static String ISNULL = "= null;"; +} diff --git a/src/com/taover/db/GenerateDao.java b/src/com/taover/db/GenerateDao.java new file mode 100644 index 0000000..0c7f5b2 --- /dev/null +++ b/src/com/taover/db/GenerateDao.java @@ -0,0 +1,144 @@ +package com.taover.db; + +import java.io.File; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import com.taover.base.template.model.dao.DaoModel; +import com.taover.base.template.model.dao.FunctionModel; +import com.taover.tools.StringUtil; +import freemarker.template.Configuration; +import freemarker.template.Template; + +public class GenerateDao { + + public static void table2dao(String filePath,String packagePath, Vector tableColumns, String dbType) throws Exception { + + String sTableName = tableColumns.get(0).getTableName(); + String sTableSchema = tableColumns.get(0).getTableSchema(); + String sJavaBeanName = tableColumns.get(0).getTableBeanUName(); + String packageBeanPath = packagePath + sJavaBeanName.toLowerCase() + ";"; + String sFileName = filePath + sJavaBeanName.toLowerCase() + ""; + + + // 生成dao的模板 + DaoModel cif = new DaoModel(); + cif.setPackages(packageBeanPath.toLowerCase()); + cif.setUsers("com.taover"); + cif.setVersion("1.0"); + cif.setBeanName(sJavaBeanName); + cif.setTableName(sTableName); + cif.setDbType(dbType); + + //设置主键信息 + TableColumn pkcolum = TableColumn.getPKColum(tableColumns); + cif.setPkBeanName(pkcolum.getColumBeanUName()); + cif.setPkColumName(pkcolum.getColumnName()); + cif.setPkType(pkcolum.getJAVADataType()); + + //insert select 时的字段列表串 + cif.setColumn_list_str(Tools.getColumnListStr(tableColumns, sTableName)); + + //设置数据库字段 + cif.setColumnList(Tools.getColums(tableColumns)); + //生成requset to po函数需要的字符串Map + cif.setReqParameterToPOMap(getReqParameterToPOMap(tableColumns)); + + // 生成引入 + generateImports(cif, packageBeanPath, sJavaBeanName); + + // 生成属性以及get,set方法 + //generateGetSetMethod(cif, sTableSchema); + + File f = new File(Tools.getPath() + Constants.TEMPATE_PATH); + Configuration cfg = new Configuration(); + cfg.setDirectoryForTemplateLoading(f); + + StringWriter out = new StringWriter(); + Template template = cfg.getTemplate(Constants.TEMPATE_DAONAME, "UTF-8"); + template.process(cif, out); + + Tools.createFile(sFileName, sJavaBeanName + "Dao.java", out.toString()); + + } + + public static void generateGetSetMethod(DaoModel cif, String sTableSchema) { + List paramlist = new ArrayList(); + + + + paramlist.add("@Resource"); + paramlist.add("private JdbcTemplate jdbcegroceryRead;"); + paramlist.add("@Resource"); + paramlist.add("private JdbcTemplate jdbcegroceryWrite;"); + paramlist.add("private Logger logger = Logger.getLogger(this.getClass());"); + List functionList = generateGetSetFunction(paramlist); + cif.setFunlist(functionList); + + cif.setPropertys(paramlist); + } + + public static void generateImports(DaoModel cif, String packagebeanpath, String javaBeanName) { + List importlist = new ArrayList(); + importlist.add("import java.util.*;"); + importlist.add("import org.apache.log4j.Logger;"); + importlist.add("import org.springframework.jdbc.core.JdbcTemplate;"); + importlist.add("import org.springframework.stereotype.Repository;"); + importlist.add("import org.apache.commons.logging.LogFactory;"); + importlist.add("import org.apache.commons.logging.Log;"); + importlist.add("import javax.annotation.Resource;"); + + importlist.add("import com.taover.tools.JdbcUtil;"); + importlist.add("import com.taover.tools.StringUtil;"); + importlist.add("import com.taover.tools.StringUtils;"); + importlist.add("import com.taover.tools.DAORowMapper;"); + importlist.add("import com.taover.tools.LogUtils;"); + cif.setImports(importlist); + } + + public static List generateGetSetFunction(List params) { + List functionList = new ArrayList(); + for (int i = 0; i < params.size(); i++) { + FunctionModel getModel = new FunctionModel(); + FunctionModel setModel = new FunctionModel(); + String[] param = params.get(i).split(" "); + getModel.setFunction_return(param[1]); + if (param[2].equalsIgnoreCase("isLogInfo")) { + getModel.setFunction_name("isLogInfo"); + setModel.setFunction_name(Constants.KEY_WORD[2] + "LogInfo"); + } else { + getModel.setFunction_name(Constants.KEY_WORD[1] + StringUtil.getFunctionName(param[2])); + setModel.setFunction_name(Constants.KEY_WORD[2] + StringUtil.getFunctionName(param[2])); + } + getModel.setFunction_body(Constants.KEY_WORD[0] + " " + param[2] + ";"); + setModel.setFunction_params(param[1] + " " + param[2]); + setModel.setFunction_return(Constants.KEY_WORD[3]); + setModel.setFunction_body(Constants.KEY_WORD[4] + param[2] + " = " + param[2] + ";"); + functionList.add(getModel); + functionList.add(setModel); + } + return functionList; + } + + public static Map getReqParameterToPOMap(Vector tableColumns) { + Map reqParameterToPOMap = new LinkedHashMap(); + if (tableColumns == null || tableColumns.size() == 0) + return reqParameterToPOMap; + for (int i = 0; i < tableColumns.size(); i++) { + String sInputName = tableColumns.get(i).getColumBeanLName(); + String sColumBeanName = tableColumns.get(i).getColumBeanUName(); + String poLine =null; + if(tableColumns.get(i).getDecimalDigits()!=0){ + poLine = sColumBeanName + "((" + tableColumns.get(i).getJAVADataType()+ ") StringUtil.StringToObj((String) map.get(\""+ sInputName + "\"), " + 9999 + "))"; + }else{ + poLine = sColumBeanName + "((" + tableColumns.get(i).getJAVADataType()+ ") StringUtil.StringToObj((String) map.get(\""+ sInputName + "\"), " + tableColumns.get(i).getDataType() + "))"; + } + reqParameterToPOMap.put(sColumBeanName, poLine); + } + return reqParameterToPOMap; + } +} diff --git a/src/com/taover/db/GenerateDaoPO.java b/src/com/taover/db/GenerateDaoPO.java new file mode 100644 index 0000000..1b4f6fb --- /dev/null +++ b/src/com/taover/db/GenerateDaoPO.java @@ -0,0 +1,103 @@ +package com.taover.db; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.Vector; + + + + +/* + * 如果列是自增长;在数据库描述中需要进行如下描述seq|属性描述 + * 不支持联合主键 + * 同时如果有自己的sequence 则命名规则如下: + * "SEQ_" + TableSchema + "_" + TableName + "_" + ColumnName + * SEQ_schame_tablename(SEQ_EGROCERY_DEVEL_SS_SKU_SKU_ID) + * + */ + +public class GenerateDaoPO { + + public static void main(String[] args) throws Exception{ + + //读取配置文件 + Properties properties = Tools.getProperties(); + //取数据库连接 + Connection conn = Tools.getConnection(properties); + //初始化要生成的表列表 + List tableNameList = new ArrayList(); + + String outputPath = properties.getProperty("OutputPath"); + String schameName = properties.getProperty("SchameName"); + String createSchame = properties.getProperty("CreateSchame"); + String dbLikeStr = properties.getProperty("DBLikeStr"); + String dbType = properties.getProperty("dbtype"); + String dbPackagePath = properties.getProperty("packageName"); + String tableName = properties.getProperty("TableName"); + if("mysql".equalsIgnoreCase(dbType)){ + //schameName = schameName.toUpperCase(); + + } + + if (!dbPackagePath.substring(dbPackagePath.length()-1).equals(".")) + dbPackagePath += "."; + + if (createSchame.equalsIgnoreCase("true") || "ALL".equalsIgnoreCase(tableName) ) { + + String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '"+schameName+"'"; + ResultSet rs = Tools.executeQuery(Tools.createStmt(conn), sql); + if (null == rs) + return ; + List result = new ArrayList(); + try { + while (rs.next()) { + tableNameList.add(rs.getString("Table_name")); + } + } catch (SQLException e) { + e.printStackTrace(); + result = null; + } + Tools.close(rs); + } else { + if("mysql".equalsIgnoreCase(dbType)){ +// tableName = tableName.toUpperCase(); + } + String[] TableNameArr = tableName.split(","); + for (int i = 0; i < TableNameArr.length; i++) + tableNameList.add(TableNameArr[i]); + + } + + for (int i = 0; i < tableNameList.size(); i++) { + + String tableNameCurr = (String) tableNameList.get(i); + + + // 取得表中所有列 + Vector columnsInTable = TableColumn.GetTableInfo(conn, schameName, tableNameCurr, dbLikeStr, dbType); + if (columnsInTable == null || columnsInTable.size() == 0) { + System.out.println(tableNameCurr + " : 生成失败,得不到表中列明"); + continue; + } + TableColumn pkcolum = TableColumn.getPKColum(columnsInTable); + if (pkcolum == null) { + System.out.println(tableNameCurr + " : 生成失败,未设置主键"); + continue; + } + + + // 生成po类 + GeneratePO.generatePO(outputPath, dbPackagePath, columnsInTable); + // 生成Dao + GenerateDao.table2dao(outputPath, dbPackagePath, columnsInTable, dbType); + System.out.println(tableNameCurr + " : 生成结束"); + } + conn.close(); + System.out.println("全部结束"); + + } +} diff --git a/src/com/taover/db/GeneratePO.java b/src/com/taover/db/GeneratePO.java new file mode 100644 index 0000000..c681f88 --- /dev/null +++ b/src/com/taover/db/GeneratePO.java @@ -0,0 +1,89 @@ +package com.taover.db; + +import java.io.File; +import java.io.StringWriter; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; + +import com.taover.base.template.model.po.ColumnModel; +import com.taover.base.template.model.po.PoModel; +import com.taover.base.template.model.po.TableModel; + +import com.taover.tools.StringUtil; +import freemarker.template.Configuration; +import freemarker.template.Template; + +public class GeneratePO { + public static void generatePO(String sOutputPath, String sDBPackagePath, Vector ColumnsInTable) throws Exception { + + String sJavaBeanName = ColumnsInTable.get(0).getTableBeanUName(); + String sTableName = ColumnsInTable.get(0).getTableName(); + String sPackagePath = sDBPackagePath + ColumnsInTable.get(0).getTableBeanLName(); + + TableModel tm = CreatePoModel(ColumnsInTable); + StringWriter out = new StringWriter(); + + PoModel cif = new PoModel(); + cif.setPackages(sPackagePath.toLowerCase() + ";"); + cif.setUsers("taover.com"); + cif.setVersion("1.0"); + cif.setName(sJavaBeanName); + cif.setToStringMethodBody(getPOToString(ColumnsInTable)); + cif.setTablemodel(tm); + + File f = new File(Tools.getPath() + Constants.TEMPATE_PATH); + Configuration cfg = new Configuration(); + cfg.setDirectoryForTemplateLoading(f); + Template template = cfg.getTemplate(Constants.TEMPATE_PONAME); + template.process(cif, out); + String filePoPath = sOutputPath + StringUtil.formatBeanNameFirstLow(sTableName); + Tools.createFile(filePoPath.toLowerCase(), sJavaBeanName + "PO.java", out.toString()); + } + public static TableModel CreatePoModel(Vector ColumnsInTable) throws Exception { + TableModel tm = new TableModel(); + List clist = new ArrayList(); + int len = ColumnsInTable.size(); + for (int i = 0; i < len; i++) { + TableColumn colum = ColumnsInTable.get(i); + ColumnModel cm = new ColumnModel(); + String sColumnBeanName = colum.getColumBeanLName(); + String sSetColumnBeanName = colum.getColumBeanUName(); + cm.setColumnName(sColumnBeanName); + cm.setColumnMethodName(sSetColumnBeanName); + cm.setColumnRemarks(colum.getRemarks()); + cm.setColumnJAVAType(colum.getJAVADataType()); + clist.add(cm); + } + tm.setColumnlist(clist); + tm.setTableName(ColumnsInTable.get(0).getTableName()); + return tm; + } + + public static String getPOToString(Vector ColumnsInTable) throws SQLException { + StringBuffer returnbuffer = new StringBuffer(); + returnbuffer.append("["); + int iLen = ColumnsInTable.size() - 1; + for (int i = 0; i <= iLen; i++) { + TableColumn colum = ColumnsInTable.get(i); + String tempName = colum.getColumBeanLName(); + if (i == iLen) { + if (i == 0) { + returnbuffer.append(tempName).append("=").append("\"").append("+").append(tempName); + }else{ + returnbuffer.append("\",").append(tempName).append("=").append("\"").append("+").append(tempName); + } + + } else { + if (i == 0) { + returnbuffer.append(tempName).append("=").append("\"").append("+").append(tempName).append("+"); + }else{ + returnbuffer.append("\",").append(tempName).append("=").append("\"").append("+").append(tempName).append("+"); + } + } + } + returnbuffer.append("+\"]\""); + return returnbuffer.toString(); + } +} diff --git a/src/com/taover/db/TableColumn.java b/src/com/taover/db/TableColumn.java new file mode 100644 index 0000000..4dab580 --- /dev/null +++ b/src/com/taover/db/TableColumn.java @@ -0,0 +1,491 @@ +package com.taover.db; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Vector; + + + +import com.taover.tools.StringUtil; + +public class TableColumn { + + + protected String tableCatalog; + protected String tableSchema; + protected String tableName; + protected String columnName; + protected int dataType; + protected String typeName; + protected int columnSize; + protected int bufferLength; + protected int decimalDigits; + protected int numPrecRadix; + protected boolean nullable; + protected String remarks; + protected String columnDefaults;//LONG + protected int sqlDataType; + protected int sqlDatatimeSubject; + protected int charOctetLength; + protected int ordinalPosition; + protected String is_nullable; + + //for mysql + protected String scopeCatalog; + protected String scopeSchema; + protected String scopeTable; + protected int sourceDataType; + protected String isAutoIncrement; + + protected String seqName; + protected boolean primaryKey; + protected String dic; + + + public String getTableCatalog() { + return tableCatalog; + } + public void setTableCatalog(String tableCatalog) { + this.tableCatalog = tableCatalog; + } + public String getTableSchema() { + return tableSchema; + } + public void setTableSchema(String tableSchema) { + this.tableSchema = tableSchema; + } + public String getTableName() { + return tableName; + } + public void setTableName(String tableName) { + this.tableName = tableName; + } + public String getColumnName() { + return columnName; + } + public void setColumnName(String columnName) { + this.columnName = columnName; + } + public int getDataType() { + return dataType; + } + public String getTypeName() { + return typeName; + } + public void setTypeName(String typeName) { + this.typeName = typeName; + } + public int getColumnSize() { + return columnSize; + } + public void setColumnSize(int columnSize) { + this.columnSize = columnSize; + } + public int getBufferLength() { + return bufferLength; + } + public void setBufferLength(int bufferLength) { + this.bufferLength = bufferLength; + } + public int getDecimalDigits() { + return decimalDigits; + } + public void setDecimalDigits(int decimalDigits) { + this.decimalDigits = decimalDigits; + } + public int getNumPrecRadix() { + return numPrecRadix; + } + public void setNumPrecRadix(int numPrecRadix) { + this.numPrecRadix = numPrecRadix; + } + public boolean isNullable() { + return nullable; + } + public void setNullable(boolean nullable) { + this.nullable = nullable; + } + public String getRemarks() { + return remarks; + } + public void setRemarks(String remarks) { + if (remarks == null || remarks.isEmpty() || remarks.equalsIgnoreCase("null")) + this.remarks = ""; + else { + remarks.trim(); + remarks = remarks.replaceAll("\\r", ""); + remarks = remarks.replaceAll("\\n", ""); + this.remarks = remarks; + } + } + public String getColumnDefaults() { + return columnDefaults; + } + public void setColumnDefaults(String columnDefaults) { + if (columnDefaults == null || columnDefaults.isEmpty() || columnDefaults.equalsIgnoreCase("null")) + this.columnDefaults = ""; + else { + columnDefaults.trim(); + columnDefaults = columnDefaults.replaceAll("\\r", ""); + columnDefaults = columnDefaults.replaceAll("\\n", ""); + this.columnDefaults = columnDefaults; + } + } + public int getSqlDataType() { + return sqlDataType; + } + public void setSqlDataType(int sqlDataType) { + this.sqlDataType = sqlDataType; + } + public int getSqlDatatimeSubject() { + return sqlDatatimeSubject; + } + public void setSqlDatatimeSubject(int sqlDatatimeSubject) { + this.sqlDatatimeSubject = sqlDatatimeSubject; + } + public int getCharOctetLength() { + return charOctetLength; + } + public void setCharOctetLength(int charOctetLength) { + this.charOctetLength = charOctetLength; + } + public int getOrdinalPosition() { + return ordinalPosition; + } + public void setOrdinalPosition(int ordinalPosition) { + this.ordinalPosition = ordinalPosition; + } + public String getIs_nullable() { + return is_nullable; + } + public void setIs_nullable(String is_nullable) { + this.is_nullable = is_nullable; + } + public String getSeqName() { + return seqName; + } + public void setSeqName(String seqName) { + this.seqName = seqName; + } + public boolean isPrimaryKey() { + return primaryKey; + } + public void setPrimaryKey(boolean primaryKey) { + this.primaryKey = primaryKey; + } + public String getDic() { + return dic; + } + + public void setDic(String dic) { + this.dic = dic; + } + + public String getScopeCatalog() { + return scopeCatalog; + } + public void setScopeCatalog(String scopeCatalog) { + this.scopeCatalog = scopeCatalog; + } + public String getScopeSchema() { + return scopeSchema; + } + public void setScopeSchema(String scopeSchema) { + this.scopeSchema = scopeSchema; + } + public String getScopeTable() { + return scopeTable; + } + public void setScopeTable(String scopeTable) { + this.scopeTable = scopeTable; + } + public int getSourceDataType() { + return sourceDataType; + } + public void setSourceDataType(int sourceDataType) { + this.sourceDataType = sourceDataType; + } + public String getIsAutoIncrement() { + return isAutoIncrement; + } + public void setIsAutoIncrement(String isAutoIncrement) { + this.isAutoIncrement = isAutoIncrement; + } + + public void setPrimaryKey(String sPKColumName) throws SQLException { + if (sPKColumName.equalsIgnoreCase(columnName)) + primaryKey = true; + } + + public void setPrimaryKey(int primarykey) { + if (primarykey != 0) + this.primaryKey = true; + else + this.primaryKey = false; + } + + public void setPrimaryKey(ResultSet rs) throws SQLException { + String columnname = rs.getString("COLUMN_NAME").trim(); + if (columnname.equalsIgnoreCase(this.columnName)) + this.primaryKey = true; + } + + public String toString() { + return "tableCatalog=" + tableCatalog + "," + + "tableSchema=" + tableSchema + "," + + "tableName=" + tableName + "," + + "columnName=" + columnName + "," + + "dataType=" + dataType + "," + + "typeName=" + typeName + ";," + + "columnSize=" + columnSize + "," + + "bufferLength=" + bufferLength + "," + + "decimalDigits=" + decimalDigits + "," + + "numPrecRadix=" + numPrecRadix + "," + + "nullable=" + nullable + "," + + "remarks=" + remarks + "," + + "columnDefaults=" + columnDefaults + "," + + "sqlDataType=" + sqlDataType + "," + + "sqlDatatimeSubject=" + sqlDatatimeSubject + "," + + "charOctetLength=" + charOctetLength + "," + + "ordinalPosition=" + ordinalPosition + "," + + "Is_Nullable=" + is_nullable + "," + + "seq=" + seqName + "," + + "PrimaryKey=" + primaryKey + "," + + "dic=" + dic; + } + + public TableColumn() { + setTableCatalog(""); + setTableSchema(""); + setTableName(""); + setColumnName(""); + setDataType(0); + setTypeName(""); + setColumnSize(0); + setBufferLength(0); + setDecimalDigits(0); + setNumPrecRadix(0); + setNullable(false); + setColumnDefaults(""); + setSqlDataType(0); + setSqlDatatimeSubject(0); + setCharOctetLength(0); + setOrdinalPosition(0); + setIs_nullable(""); + + + setSeqName(""); + setPrimaryKey(false); + setDic(""); + } + + public TableColumn(ResultSet rs, String dbType) throws SQLException { + + setTableCatalog(rs.getString("TABLE_CAT")); + setTableSchema(rs.getString("TABLE_SCHEM")); + if (getTableSchema() == null && dbType.equalsIgnoreCase("mysql")) + setTableSchema(getTableCatalog()); + setTableName(rs.getString("TABLE_NAME").trim()); + setColumnName(rs.getString("COLUMN_NAME").trim()); + //setColumnSize 一定要在DataType之前,否则会影响返回的JAVA类型 + setColumnSize(rs.getInt("COLUMN_SIZE")); + setTypeName(rs.getString("TYPE_NAME").trim()); + setDecimalDigits(rs.getInt("DECIMAL_DIGITS")); + setDataType(rs.getInt("DATA_TYPE")); + setBufferLength(rs.getInt("BUFFER_LENGTH")); + setNumPrecRadix(rs.getInt("NUM_PREC_RADIX")); + setNullable(rs.getBoolean("NULLABLE")); + setColumnDefaults(rs.getString("COLUMN_DEF")); + setSqlDataType(rs.getInt("SQL_DATA_TYPE")); + setSqlDatatimeSubject(rs.getInt("SQL_DATETIME_SUB")); + setCharOctetLength(rs.getInt("CHAR_OCTET_LENGTH")); + setOrdinalPosition(rs.getInt("ORDINAL_POSITION")); + setIs_nullable(rs.getString("IS_NULLABLE")); + setRemarks(rs.getString("REMARKS")); + + if (dbType.equalsIgnoreCase("mysql")) { + setScopeCatalog(rs.getString("SCOPE_CATALOG")); + setScopeSchema(rs.getString("SCOPE_SCHEMA")); + setScopeTable(rs.getString("SCOPE_TABLE")); + setSourceDataType(rs.getInt("SOURCE_DATA_TYPE")); + setIsAutoIncrement(rs.getString("IS_AUTOINCREMENT")); + } + if (null != remarks && !remarks.isEmpty()) { + int iStartPos = remarks.indexOf("seq"); + int iSplitPos = remarks.indexOf("|"); + // 存在seq 设置 + if (iStartPos >= 0 && iSplitPos >0) { + String seq_setting = remarks.substring(iStartPos); + int iEndPos = seq_setting.indexOf("|", iStartPos); + String rem = remarks.substring(0, iStartPos); + if (iEndPos >= 0) { + seq_setting = seq_setting.substring(0, iEndPos); + rem += remarks.substring(iEndPos + 1); + } + //setRemarks(rem); + String arr[] = seq_setting.split("="); + + if (arr.length == 2) { + setSeqName(arr[1]); + } else { + setSeqName("SEQ_" + getTableSchema() + "_" + getTableName() + "_" + getColumnName()); + } + } + } else { + //setRemarks(this.columnName); + } + } + + public void setDataType(int datatype) { + this.dataType = datatype; + //orcale 下, 91同93 +// if ((datatype == 91)) +// this.dataType = 93; + if ((datatype == 1111) && getTypeName().length()>=9&&(getTypeName().substring(0, 9).equalsIgnoreCase("TIMESTAMP"))) + this.dataType = 93; + + if (((datatype == 2) || (datatype == 3)) && (this.decimalDigits == 0)) { + if (this.columnSize < 3) { + this.dataType = -6; + } else if (this.columnSize < 5) { + this.dataType = 5; + } else if (this.columnSize < 11) + this.dataType = 4; + else + this.dataType = -5; + } + } + + public String getJAVADataType() { + switch (this.dataType) { + case -101: + return "oracle.sql.TIMESTAMPTZ"; + case -102: + return "oracle.sql.TIMESTAMPLTZ"; + case -7: + return "Boolean"; + case -6: + return "Byte"; + case -5: + return "Long"; + case -4: + case -3: + case -2: + return "byte[]"; + case -1: + return "String"; + case 1: + return "String"; + case 2: + case 3: + if (this.decimalDigits != 0) { + return "java.math.BigDecimal"; + } + return "Long"; + case 4: + return "Integer"; + case 5: + return "Short"; + case 6: + return "Float"; + case 7: + case 8: + return "Double"; + case 12: + return "String"; + case 91: + return "java.util.Date"; + case 92: + return "java.sql.Time"; + case 93: + return "java.sql.Timestamp"; + case 1111: + case 2004: + case 2005: + return "String"; + } + return ""; + } + + public String getTableBeanUName() { + return StringUtil.formatBeanNameFirstUpper(getTableName()); + } + + public String getTableBeanLName() { + return StringUtil.formatBeanNameFirstLow(getTableName()); + } + + public String getColumBeanUName() { + return StringUtil.formatBeanNameFirstUpper(this.columnName); + } + + public String getColumBeanLName() { + return StringUtil.formatBeanNameFirstLow(this.columnName); + } + + public static Vector GetTableInfo(Connection Conn, String schameName, String sTableName, String likeStr, String dbType) { + + Vector ColumnsInTable = new Vector(); + try { + + DatabaseMetaData dbmd = Conn.getMetaData(); + ResultSet rs = dbmd.getColumns(null, schameName, sTableName, likeStr); + if (rs == null) { + System.out.println("The Result Set is null "); + return null; + } + while (rs.next()) { + TableColumn tableColumns = new TableColumn(rs, dbType); + ColumnsInTable.addElement(tableColumns); + } + setPrimaryKey(Conn, likeStr, ColumnsInTable); + rs.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return ColumnsInTable; + } + + public static void setPrimaryKey (Connection Conn, String likeStr, Vector Colums) { + + try { + DatabaseMetaData dbmd = Conn.getMetaData(); + if (Colums == null || Colums.size() < 0) + return; + ResultSet rs = dbmd.getPrimaryKeys(Colums.get(0).getTableCatalog(), Colums.get(0).getTableSchema(), Colums.get(0).getTableName()); + while (rs.next()) { + String sPKColumName = rs.getString("COLUMN_NAME").trim(); + for (int i = 0; i < Colums.size(); i++) { + TableColumn tc = Colums.get(i); + tc.setPrimaryKey(sPKColumName); + } + } + rs.close(); + } + catch (SQLException e) { + e.printStackTrace(); + } + return; + } + + public static TableColumn getPKColum(Vector Colums) { + if (Colums == null || Colums.size() == 0) + return null; + for (int i = 0; i < Colums.size(); i++) { + if (Colums.get(i).isPrimaryKey()) { + return Colums.get(i); + } + } + return null; + } + + public static TableColumn getColumFromListByName(Vector ColumList, String sColumnName) { + for (int i = 0; ColumList != null && i < ColumList.size(); i++) { + if (ColumList.get(i).getColumnName().equalsIgnoreCase(sColumnName)) + return ColumList.get(i); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/taover/db/Tools.java b/src/com/taover/db/Tools.java new file mode 100644 index 0000000..475f25b --- /dev/null +++ b/src/com/taover/db/Tools.java @@ -0,0 +1,287 @@ +package com.taover.db; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.StringTokenizer; +import java.util.Vector; + +import com.taover.db.GenerateDaoPO; + +import com.taover.base.template.model.po.ColumnModel; +import com.taover.tools.StringUtil; + +public class Tools { + + private static String path = null; + private static String resourcesPath = null; + + public static Connection getConnection(Properties properties) { + Connection conn = null; + try { + Class.forName(properties.getProperty("driver")); + Properties prop = new Properties(); + prop.setProperty("user", properties.getProperty("User")); + prop.setProperty("password", properties.getProperty("Password")); + prop.setProperty("remarks", "true"); + conn = DriverManager.getConnection(properties.getProperty("URL"), + prop); + } catch (Exception e) { + e.printStackTrace(); + } + return conn; + } + + public static String getPath() { + + //兼容传入path使用 + if(path != null){ + return path; + } + + GenerateDaoPO td = null; + String str = null; + try { + td = new GenerateDaoPO(); + str = System.getProperty("user.dir") + File.separator + "bin"; + } catch (Exception e) { + str = "."; + e.printStackTrace(); + } + return str; + + + } + + public static String getResourcesPath() { + return resourcesPath; + + } + public static void setResourcesPath(String resourcesPath) { + Tools.resourcesPath = resourcesPath; + } + + public static void setPath(String path) { + Tools.path = path; + } + + public static Properties getProperties(String propertiesName) { + Properties properties = null; + try { + properties = new Properties(); + InputStream inputStream = new FileInputStream(getResourcesPath() +File.separator +propertiesName + ".properties"); + properties.load(inputStream); + inputStream.close(); + } catch (Exception e) { + properties = null; + e.printStackTrace(); + } + return properties; + } + + public static Properties getProperties() { + Properties properties = null; + try { + properties = new Properties(); + InputStream inputStream = new FileInputStream(getPath() +File.separator + + "default.properties"); + properties.load(inputStream); + inputStream.close(); + } catch (Exception e) { + properties = null; + e.printStackTrace(); + } + return properties; + } + public static Properties getProductProperties() { + Properties properties = null; + try { + properties = new Properties(); + InputStream inputStream = new FileInputStream(getPath()+File.separator + + "product.properties"); + properties.load(inputStream); + inputStream.close(); + } catch (Exception e) { + properties = null; + e.printStackTrace(); + } + return properties; + } + + public static String getColumnListStr(Vector tableColumns, + String tableName) throws SQLException { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < tableColumns.size(); i++) { + if (i == tableColumns.size() - 1) { + sb.append(tableColumns.get(i).getColumnName()); + break; + } + if (tableColumns.get(i).getColumnName().equals("check")) { + sb.append("\\\"" + tableColumns.get(i).getColumnName() + + "\\\", "); + } else { + sb.append(tableColumns.get(i).getColumnName() + ", "); + } + } + return sb.toString(); + } + + public static List getColums(Vector tableColumns) { + if (tableColumns == null || tableColumns.size() == 0) + return null; + List list = new ArrayList(); + for (int i = 0; i < tableColumns.size(); i++) { + String sColumnDBName = tableColumns.get(i).getColumnName(); + String sColumnBeanName = StringUtil.formatBeanNameFirstLow(sColumnDBName); + ColumnModel cm = new ColumnModel(); + cm.setColumnName(sColumnDBName); + cm.setColumnMethodName(sColumnBeanName); + cm.setColumnRemarks(tableColumns.get(i).getRemarks()); + cm.setColumnUName(StringUtil + .formatBeanNameFirstUpper(sColumnDBName)); + String seq = tableColumns.get(i).getSeqName(); + if (seq != null && !seq.isEmpty()) { + cm.setSeqName(seq); + } + cm.setColumnJAVAType(tableColumns.get(i).getJAVADataType()); + list.add(cm); + } + return list; + } + + public static void createFile(String path, String filename, String incontent) + throws IOException { + java.io.File file = new java.io.File(path + File.separator + filename); + createFile(path); + if (file.exists() && file.isFile()) + file.delete(); + if (!file.exists()) + file.createNewFile(); + + try { + FileOutputStream out = new FileOutputStream(path + File.separator+ filename); + PrintStream p = new PrintStream(out); + p.println(incontent); + out.close(); + p.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + } + + public static void createFile(String path) { + File tempFile = new File(path); + tempFile.mkdirs(); + + + /*StringTokenizer st = new StringTokenizer(path, File.separator); + String path1 = st.nextToken() + File.separator; + String path2 = path1; + while (st.hasMoreTokens()) { + path1 = st.nextToken() + File.separator; + path2 += path1; + File inbox = new File(path2); + if (!inbox.exists()) + inbox.mkdir(); + }*/ + } + + public static Statement createStmt(Connection conn) { + Statement stmt = null; + try { + stmt = conn.createStatement(); + } catch (SQLException e) { + e.printStackTrace(); + } + return stmt; + } + + public static int executeUpdate(Connection conn, String sql) { + Statement stmt = null; + int ret = 0; + try { + stmt = conn.createStatement(); + ret = stmt.executeUpdate(sql); + } catch (SQLException e) { + e.printStackTrace(); + } + return ret; + } + + public static PreparedStatement prepareStmt(Connection conn, String sql) { + PreparedStatement pStmt = null; + try{ + pStmt = conn.prepareStatement(sql); + } catch (SQLException e) { + e.printStackTrace(); + } + return pStmt; + } + + public static PreparedStatement prepareStmt(Connection conn, String sql, int autoGeneratedKeys) { + PreparedStatement pStmt = null; + try{ + pStmt = conn.prepareStatement(sql, autoGeneratedKeys); + } catch (SQLException e) { + e.printStackTrace(); + } + return pStmt; + } + + public static ResultSet executeQuery(Statement stmt, String sql) { + ResultSet rs = null; + try { + rs = stmt.executeQuery(sql); + } catch (SQLException e) { + e.printStackTrace(); + } + return rs; + } + + public static void close(Connection conn) { + if(conn != null) { + try { + conn.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + conn = null; + } + } + + public static void close(Statement stmt) { + if(stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + stmt = null; + } + } + + public static void close(ResultSet rs) { + if(rs != null) { + try { + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + rs = null; + } + } +} diff --git a/src/com/taover/tools/StringUtil.java b/src/com/taover/tools/StringUtil.java new file mode 100644 index 0000000..4254157 --- /dev/null +++ b/src/com/taover/tools/StringUtil.java @@ -0,0 +1,565 @@ +package com.taover.tools; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.math.BigDecimal; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class StringUtil { + + public static int strToInt(String s, int def) { + try { + return Integer.parseInt(s); + } catch (Exception e) { + return def; + } + } + + public static String getFunctionName(String paramName) { + String functionName = null; + + if (paramName.length() > 1) { + functionName = paramName.substring(0, 1).toUpperCase() + + paramName.substring(1, paramName.length()); + } else { + functionName = paramName.toUpperCase(); + + } + return functionName; + } + + public static Date StringToDate(String sDate, String sFormat) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat(sFormat); + return sdf.parse(sDate); + } + + public static java.sql.Timestamp StringToTimestamp(String sDate, String sFormat) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat(sFormat); + Date t = sdf.parse(sDate); + return new java.sql.Timestamp(t.getTime()); + + } + + public static Object StringToObj(String s, int type) { + try { + switch (type) { + case -7: + return Boolean.parseBoolean(s); + case -6: + return Byte.parseByte(s); + case 5: + return Short.parseShort(s); + case 4: + return Integer.parseInt(s); + case -5: + return Long.parseLong(s); + case 6: + return Float.parseFloat(s); + case 7: + case 8: + return Double.parseDouble(s); + case 2: + case 3: + return Integer.parseInt(s); + case 91: + return StringToDate(s, "yyyy-MM-dd HH:mm:ss"); + case 92: + case 93: + return StringToTimestamp(s, "yyyy-MM-dd HH:mm:ss"); + case 100: + return StringToTimestamp(s+" 00:00:00", "yyyy-MM-dd HH:mm:ss"); + case 101: + return StringToTimestamp(s+" 23:59:59", "yyyy-MM-dd HH:mm:ss"); + case 9999: + return new BigDecimal(s); + default: + return s; + } + + } catch (Exception e) { + return null; + } + } + + public static String getJavaType(int type, int scale) { + String javaType = ""; + switch (type) { + case -7: + javaType = "Boolean"; + case -6: + // return "byte"; + javaType = "java.sql.Blob"; + case 5: + // return "short"; + javaType = "java.math.BigDecimal"; + case 4: + // return "integer"; + javaType = "Integer"; + case -5: + // return "long"; + javaType = "Long"; + case 6: + // return "float"; + javaType = "java.math.BigDecimal"; + case 7: + case 8: + // return "double"; + javaType = "java.math.BigDecimal"; + break; + case 2: + case 3: + // if (this.decimalDigits != 0) { + // return "double"; + // } + // return "long"; + if (scale != 0) { + javaType = "java.math.BigDecimal"; + } else { + javaType = "Integer"; + } + break; + case 91: + case 92: + case 93: + // return "date"; + javaType = "java.util.Date"; + break; + default: + javaType = "String"; + + } + return javaType; + } + + public static Date strToFormatDate(String date, String format) { + if (date == null) return null; + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.parse(date, new ParsePosition(0)); + } + + /** + * 将字符串转换为yyyy-MM-dd格式的日期 + * + * @param date + * @return 转换后的日期对象 + */ + public static Date strToDate(String date) { + return StringUtil.strToFormatDate(date, "yyyy-MM-dd"); + } + + /** + * 将字符串转换为yyyy-MM-dd HH:mm:ss格式的日期 + * + * @param date + * @return 转换后的日期对象 + */ + public static Date strToDateTime(String date) { + return StringUtil.strToFormatDate(date, "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 将date型日期转换成特定格式的时间字符串 + * + * @param date + * @param format + * @return 转换后的日期对象 + */ + public static String dateToFormatStr(Date date, String format) { + if (date == null) return null; + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(date); + } + + /** + * 将date型日期转换成yyyy-MM-dd HH:mm:ss格式的时间字符串 + * + * @param date + * 日期 + * @return 返回yyyy-MM-dd HH:mm格式的时间字符串 + */ + public static String dateTimeToStr(Date date) { + return StringUtil.dateToFormatStr(date, "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 将date型日期转换成yyyy-MM-dd格式的日期字符串 + * + * @param date + * 日期 + * @return 返回yyyy-MM-dd格式的日期字符串 + */ + public static String dateToStr(Date date) { + return StringUtil.dateToFormatStr(date, "yyyy-MM-dd"); + } + + /** + * 计算出date day天之前或之后的日期 + * + * @param date + * {@link Date} 日期 + * @param days + * int 天数,正数为向后几天,负数为向前几天 + * @return 返回Date日期类型 + */ + public static Date getDateBeforeOrAfterDays(Date date, int days) { + Calendar now = Calendar.getInstance(); + now.setTime(date); + now.set(Calendar.DATE, now.get(Calendar.DATE) + days); + return now.getTime(); + } + + /** + * 计算出date monthes月之前或之后的日期 + * + * @param date + * 日期 + * @param monthes + * 月数,正数为向后几天,负数为向前几天 + * @return 返回Date日期类型 + */ + public static Date getDateBeforeOrAfterMonthes(Date date, int monthes) { + Calendar now = Calendar.getInstance(); + now.setTime(date); + now.set(Calendar.MONTH, now.get(Calendar.MONTH) + monthes); + return now.getTime(); + } + + /** + * 计算出date years年之前或之后的日期 + * + * @param date + * 日期 + * @param years + * 年数,正数为向后几年,负数为向前几年 + * @return 返回Date日期类型 + */ + public static Date getDateBeforeOrAfterYears(Date date, int years) { + Calendar now = Calendar.getInstance(); + now.setTime(date); + now.set(Calendar.YEAR, now.get(Calendar.YEAR) + years); + return now.getTime(); + } + + /** + * 计算两个日期之间的天数 + * + * @param beginDate + * @param endDate + * @return 如果beginDate 在 endDate之后返回负数 ,反之返回正数 + */ + public static int daysOfTwoDate(Date beginDate, Date endDate) { + + Calendar beginCalendar = Calendar.getInstance(); + Calendar endCalendar = Calendar.getInstance(); + + beginCalendar.setTime(beginDate); + endCalendar.setTime(endDate); + + return daysOfTwoDate(beginCalendar, endCalendar); + + } + + /** + * 计算两个日期之间的天数 + * + * @param d1 + * @param d2 + * @return 如果d1 在 d2 之后返回负数 ,反之返回正数 + */ + public static int daysOfTwoDate(Calendar d1, Calendar d2) { + int days = 0; + int years = d1.get(Calendar.YEAR) - d2.get(Calendar.YEAR); + if (years == 0) {// 同一年中 + days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR); + return days; + } else if (years > 0) {// 不同一年 + for (int i = 0; i < years; i++) { + d2.add(Calendar.YEAR, 1); + days += -d2.getActualMaximum(Calendar.DAY_OF_YEAR); + if (d1.get(Calendar.YEAR) == d2.get(Calendar.YEAR)) { + days += d2.get(Calendar.DAY_OF_YEAR) + - d1.get(Calendar.DAY_OF_YEAR); + return days; + } + } + } else + for (int i = 0; i < -years; i++) { + d1.add(Calendar.YEAR, 1); + days += d1.getActualMaximum(Calendar.DAY_OF_YEAR); + if (d1.get(Calendar.YEAR) == d2.get(Calendar.YEAR)) { + days += d2.get(Calendar.DAY_OF_YEAR) + - d1.get(Calendar.DAY_OF_YEAR); + return days; + } + } + return days; + } + + /** + * 获得当前时间当天的开始时间,即当前给出的时间那一天的00:00:00的时间 + * + * @param date + * 当前给出的时间 + * @return 当前给出的时间那一天的00:00:00的时间的日期对象 + */ + public static Date getDateBegin(Date date) { + SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd"); + if (date != null) { + try { + return DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.CHINA).parse(ymdFormat.format(date)); + } catch (ParseException e) { + e.printStackTrace(); + } + } + + return null; + } + + /** + * 获得当前时间当天的结束时间,即当前给出的时间那一天的23:59:59的时间 + * + * @param date + * 当前给出的时间 + * @return 当前给出的时间那一天的23:59:59的时间的日期对象 + */ + public static Date getDateEnd(Date date) { + SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd"); + if (date != null) { + try { + date = getDateBeforeOrAfterDays(date, 1); + date = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.CHINA).parse(ymdFormat.format(date)); + Date endDate = new Date(); + endDate.setTime(date.getTime() - 1000); + return endDate; + } catch (ParseException e) { + e.printStackTrace(); + } + } + return null; + } + + public static String getTime() { + Date d = new Date(); + String re = dateToFormatStr(d, "yyyyMMddHHmm"); + return re; + } + + public static String removeLast(String str) { + str = str.trim(); + return str.substring(0, str.length() - 1); + } + + public static boolean isEmpty(String str) { + return str == null || str.trim().length() == 0 + || str.trim().equals("null"); + } + + public static int getRandom6() { + Random ran = new Random(); + int r = 0; + m1 : while (true) { + int n = ran.nextInt(1000000); + r = n; + int[] bs = new int[6]; + for (int i = 0; i < bs.length; i++) { + bs[i] = n % 10; + n /= 10; + } + Arrays.sort(bs); + for (int i = 1; i < bs.length; i++) { + if (bs[i - 1] == bs[i]) { + continue m1; + } + } + break; + } + return r; + } + + public static int getCurrentTimeHashCode() { + return String.valueOf(System.currentTimeMillis()).hashCode(); + } + + public static String randomNumString(int len) { + final int maxNum = 10; + char[] str = {'0', '1', '2', '3', '5', '6', '7', '8', '9'}; + StringBuffer randStr = new StringBuffer(""); + Random r = new Random(); + for (int i = 0, count = 0; count < len; i++) { + i = Math.abs(r.nextInt(maxNum)); + if (i >= 0 && i < str.length) { + randStr.append(str[i]); + count++; + } + } + return randStr.toString(); + } + + /** + * 随机生成指定长度的字符串 + */ + public static String randomString(int length) { + if (length < 1) { return null; } + String basicchars = "0123456789abcdefghijklmnopqrstuvwxy"; + Random randGen = new Random(); + char[] numbersAndLetters = basicchars.toCharArray(); + char[] randBuffer = new char[length]; + for (int i = 0; i < randBuffer.length; i++) { + randBuffer[i] = numbersAndLetters[randGen.nextInt(basicchars.length() - 1)]; + } + return new String(randBuffer); + } + + public static String format(String format, Object... objects) { + return String.format(format, objects); + } + + public static String Object2params(Object... params) { + String newLine = "\n"; + if ("\\".equals(File.separator)) {// windows 下 log 换行符 + newLine = "\r\n"; + } + StringBuffer info = new StringBuffer(); + info.append(newLine); + int i = 1; + if (params != null) { + for (Object param : params) { + info.append("[参数" + i + ":" + param + "]"); + info.append(newLine); + i++; + } + } + return info.toString(); + } + + public static boolean isAutowired(List condition) { + return false; + } + + public static boolean isAutowired(String condition) { + return false; + } + + public static String toUpperCaseFirstOne(String s) { + if (Character.isUpperCase(s.charAt(0))) + return s; + else + return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString(); + } + + public static String formatBeanNameFirstUpper(String name) { + if (name == null) return null; + if (name.length() == 0) return ""; + String sReturn = formatBeanNameFirstLow(name); + return toUpperCaseFirstOne(sReturn); + } + + public static String formatBeanNameFirstLow(String name) { + if (name == null) return null; + if (name.length() == 0) return ""; + byte[] ss = name.toLowerCase().getBytes(); + int len = ss.length; + byte[] ss1 = new byte[len]; + ss1[0] = ss[0]; + int k = 1; + for (int i = 1; i < ss.length; i++) { + if (ss[i] == '_') { + if (i < ss.length - 1) { + ss1[k] = (byte)Character.toUpperCase(ss[(i + 1)]); + i++; + } + len--; + } else { + ss1[k] = ss[i]; + } + k++; + } + return new String(ss1, 0, len); + } + + public static Object getObjectValue(Field field, Object target) { + Object result = null; + try { + String sMethodName = "get" + + StringUtil.toUpperCaseFirstOne(field.getName()); + Method method = target.getClass().getMethod(sMethodName, null); + result = method.invoke(target, null); + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + @SuppressWarnings("unchecked") + public static String getValueFromObjectByName(Object obj, String fiedName) { + if(!StringUtil.isEmpty(fiedName)){ + try { + String sMethodName = "get" +// + StringUtil.toUpperCaseFirstOne(fiedName); + + StringUtil.formatBeanNameFirstUpper(fiedName);//例:FIR_NAME 改成 FirName + Method method = obj.getClass().getMethod(sMethodName, null); + Object t = method.invoke(obj, null); + if(t != null) + return t.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + return null; + } + + @SuppressWarnings("unchecked") + public static Object[] getListByObject(Object obj) { + ArrayList list = new ArrayList(); + for (Field field : obj.getClass().getDeclaredFields()) { + Object result = getObjectValue(field, obj); + list.add(field.getName() + " 值: " + result); + } + return list.toArray(); + } + + + public static String replaceBlank(String str) { + String dest = ""; + if (str != null) { + Pattern p = Pattern.compile("\\s*|\t|\r|\n"); + Matcher m = p.matcher(str); + dest = m.replaceAll(""); + } + return dest; + } + + + public static String transferObjectList(List obj){ + + if(obj == null){ + return ""; + } + StringBuffer returnStr = new StringBuffer("["); + for(Object[] o : obj){ + returnStr.append(Arrays.toString(o)); + returnStr.append(","); + } + returnStr.append("]"); + + return returnStr.toString(); + + + } + +} -- libgit2 0.21.2