偷懒日志 - 自动生成代码 - 第三步 生成Dao

有了第一步、第二步、第三步咱们就可以直接生成Dao了,需要增加函数:

// 得到调用函数参数[字段、排除字段,结束字符]
function getInParams(fields, excludes, end) {
	var html = '';
	$(fields).each(function(i, item) {
		if (item != null && !isInArray(excludes, item.name)) {
			html += item.name + ', ';
		}
	});
	var index = html.lastIndexOf(', ');
	if (index > -1 && index == html.length - 2)
	{
		html = html.substr(0, html.length-2);
	}
	return html == '' ? '' : html + (!!end ? end : '');
}
// 得到函数参数[字段、排除字段,结束字符]
function getInFuncParams(fields, excludes, end) {
	var html = '';
	$(fields).each(function(i, item) {
		if (item != null && !isInArray(excludes, item.name)) {
			html += item.getFuncParams() + ', ';
		}
	});
	var index = html.lastIndexOf(', ');
	if (index > -1 && index == html.length - 2)
	{
		html = html.substr(0, html.length-2);
	}
	return html == '' ? '' : html + (!!end ? end : '');
}

以上是一些带有所有字段的dao内函数,需要对所有字段进行一个遍历。

下面是Dao中一些共性收集成Filed自带函数:

// dao中的 sql 组合 带有位置信息
Field.prototype.getDaoSql = function (space) {
	var html = '';
	if (this.isInt) {
		html += space + 'if (' + this.name + ' > 0 && ' + this.name + ' < Integer.MAX_VALUE) {\r';
		html += space + '	sql.append(" AND ' + this.name + ' = ").append(' + this.name + ');\r';
		html += space + '}\r';
	}
	else if (this.isString) {
		html += space + 'int ' + this.name + 'Pos = 0;\r';
		html += space + 'if (' + this.name + ' != null && ' + this.name + '.length() > 0) {\r';
		html += space + '	sql.append(" AND ' + this.name + ' LIKE ?");\r';
		html += space + '	' + this.name + 'Pos = ++pos;\r';
		html += space + '}\r';
	}
	else if (this.isTime) {
		html += space + 'if (' + this.name + ' != null) {\r';
		html += space + '	Timestamp time1 = TimeUtil.diff(' + this.name + ', Calendar.SECOND, -1);\r';
		html += space + '	Timestamp time2 = TimeUtil.diff(' + this.name + ', Calendar.SECOND,  1);\r';
		html += space + '	sql.append(" AND ' + this.name + ' > \'").append(time1);\r';
		html += space + '	sql.append("\' AND ' + this.name + ' < \'").append(time2).append("\'");\r';
		html += space + '}\r';
	}
	return html;
}
// dao中的 set 带有位置信息
Field.prototype.getDaoPstmt = function (space) {
	var html = '';
	if (this.isString) {
		html += space + 'if (' + this.name + 'Pos > 0) {\r';
		html += space + '	pstmt.setString(' + this.name + 'Pos, "%" + ' + this.name + ' + "%");\r';
		html += space + '}\r';
	}
	return html;
}

接下来就是Dao类生成函数了,有点长,大家耐心看看:

function getDao(packageName, beanName, table, dbName, rows, keys, pKey, isMysql, createTime)
{
	var html = 'package '+packageName+'.dao;\r\r';
	html += 'import static '+packageName+'.util.PrintUtil.print;\r\r';
	html += 'import java.sql.Connection;\r';
	html += 'import java.sql.ResultSet;\r';
	html += 'import java.sql.Timestamp;\r';
	html += 'import java.util.ArrayList;\r\r';

	html += 'import '+packageName+'.bean.' + beanName + ';\r';
	html += 'import '+packageName+'.util.DbUtil;\r';
	html += 'import '+packageName+'.util.TyStatement;\r\r';

	html += 'import org.apache.commons.logging.Log;\r';
	html += 'import org.apache.commons.logging.LogFactory;\r\r';

	html += 'public class ' + beanName + 'Dao {\r';
	html += '	private static Log logger = LogFactory.getLog(' + beanName + 'Dao.class);\r\r';
	html += '	public ' + beanName + ' get(' + pKey.getFuncParams() + ') {\r';
	html += '		Connection conn = DbUtil.getConn("' + dbName + '");\r';
	html += '		StringBuffer sql = new StringBuffer();\r';
	if (isMysql) {
		html += '		sql.append("SELECT * FROM ' + table + '");\r';
		html += '		sql.append(" WHERE ' + pKey.name + ' = ? LIMIT 1");\r\r';
	} else {
		html += '		sql.append("SELECT TOP 1 * FROM ' + table + '");\r';
		html += '		sql.append(" WHERE ' + pKey.name + ' = ?");\r\r';
	}
	
	html += '		' + beanName + ' temp = null;\r';
	html += '		TyStatement pstmt = null;\r';
	html += '		ResultSet rs = null;\r';
	html += '		try {\r';
	html += '			pstmt = new TyStatement(conn, sql);\r';
	html += '			'+ pKey.getPstmtSet(1);
	html += '			rs = pstmt.executeQuery();\r';
	html += '			if (rs.next()) {\r';
	html += '				temp = new ' + beanName + ' ();\r';
	$.each(rows, function(i, item) {
		if (item != null) {
			html += item.getSqlSet('				');
		}
	});
	html += '			}\r';
	html += getDaoFunLast(true, '		');
	html += '		return temp;\r';
	html += '	}\r\r';
	
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// getList
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	var nextKey = 'next' + pKey.upName;
	html += '	public ArrayList<' + beanName + '> getList(';
	html += getInFuncParams(keys, [pKey.name], ', ');
	if (isMysql) {
		html += 'int pageSize, int pageNum) {\r';
		html += '		if (pageSize < 0 || pageNum <= 0) return null;\r'
	} else {
		html += ''+ pKey.type +' ' + nextKey + ') {\r';
	}
	
	html += '		Connection conn = DbUtil.getConn("' + dbName + '");\r';
	html += '		StringBuffer sql = new StringBuffer();\r';
	html += '		sql.append("SELECT * FROM ' + table + ' WHERE 1 = 1");\r';
	if (!isMysql) { } // 区分LIMIT
	if (getInFuncParams(keys, [pKey.name]) != '') {
		html += '		int pos = 0;\r';
	}
	$.each(keys, function(i, item) {
		if (item != null && item != pKey)
			html += item.getDaoSql('		');
	});
	html += '		sql.append(" ORDER BY ' + pKey.name + ' DESC");\r\r';
	if (isMysql)
	{
		html += '		if (pageSize > 0) {\r';
		html += '			sql.append(" LIMIT ").append((pageNum - 1) * pageSize);\r';
		html += '			sql.append(",").append(pageSize);\r';
		html += '		}\r';
	}
	html += '		ArrayList<' + beanName + '> list = new ArrayList<' + beanName + '>();\r';
	html += '		' + beanName + ' temp = null;\r';
	html += '		TyStatement pstmt = null;\r';
	html += '		ResultSet rs = null;\r';
	html += '		try {\r';
	html += '			pstmt = new TyStatement(conn, sql);\r';
	$.each(keys, function(i, item) {
		if (item != null && item != pKey)
			html += item.getDaoPstmt('			');
	});
	html += '			rs = pstmt.executeQuery();\r';
	html += '			while (rs.next()) {\r';
	html += '				temp = new ' + beanName + '();\r';
	$.each(rows, function(i, item) {
		if (item != null)
			html += item.getSqlSet('				');
	});
	html += '				list.add(temp);\r';
	html += '			}\r';
	html += getDaoFunLast(true, '		');
	html += '		return list;\r';
	html += '	}\r';
	html += '\r';

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// getCount
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	html += '	public int getCount(' + getInFuncParams(keys, [pKey.name]) + ') {\r';
	html += '		Connection conn = DbUtil.getConn("' + dbName + '");\r';
	html += '		StringBuffer sql = new StringBuffer();\r';
	html += '		sql.append("SELECT COUNT(0) FROM ' + table + ' WHERE 1 = 1");\r';
	if (getInFuncParams(keys, [pKey.name]) != '') {
		html += '		int pos = 0;\r';
	}
	$.each(keys, function(i, item) {
		if (item != null && item != pKey)
			html += item.getDaoSql('		');
	});
	html += '		int result = 0;\r';
	html += '		TyStatement pstmt = null;\r';
	html += '		ResultSet rs = null;\r';
	html += '		try {\r';
	html += '			pstmt = new TyStatement(conn, sql);\r';
	$.each(keys, function(i, item) {
		if (item != null && item != pKey)
			html += item.getDaoPstmt('			');
	});
	html += '			rs = pstmt.executeQuery();\r';
	html += '			while (rs.next()) {\r';
	html += '				result = rs.getInt(1);\r';
	html += '			}\r';
	html += getDaoFunLast(true, '		');
	html += '		return result;\r';
	html += '	}\r';
	html += '\r';

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// insert
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	
	html += '	public int insert(' + getInFuncParams(rows, [pKey.name, createTime]) + ') {\r';
	html += '		Connection conn = DbUtil.getConn("' + dbName + '");\r';
	html += '		StringBuffer sql = new StringBuffer();\r';
	html += '		sql.append("INSERT INTO ' + table + '");\r';
	html += '		sql.append(" (' + getInParams(rows, ['id']) + ')");\r';
	html += '		sql.append(" VALUES (';
	$.each(rows, function(i, item) {
		if (item != null && item != pKey) {
			if (item.name == createTime) {
				html += 'NOW(), ';
			} else {
				html += '?, ';
			}
		}
	});
	if (html.lastIndexOf(', ') > -1 && html.lastIndexOf(', ') == html.length - 2)
	{
		html = html.substr(0, html.length-2);
	}
	html += ')");\r';
	html += '		int result = 0;\r';
	html += '		TyStatement pstmt = null;\r';
	if (pKey.name == 'id') {
		html += '		ResultSet rs = null;\r';
	}
	html += '		try {\r';
	if (pKey == 'id') {
		html += '			pstmt = new TyStatement(conn, sql, true);\r';
	} else {
		html += '			pstmt = new TyStatement(conn, sql);\r';
	}
	var k = 0;
	$.each(rows, function(i, item) {
		if (item != null && item != pKey && item.name != createTime) {
			html += '			' + item.getPstmtSet(++k);
		}
	});
	if (pKey.name == 'id') {
		html += '			pstmt.executeUpdate();\r';
		html += '			rs = pstmt.getGeneratedKeys();\r';
		html += '			if (rs.next()) {\r';
		html += '				result = rs.getInt(1);\r';
		html += '			}\r';
	} else {
		html += '			result = pstmt.executeUpdate();\r';
	}
	html += getDaoFunLast(pKey.name == 'id', '		');
	html += '		return result;\r';
	html += '	}\r\r';

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// update
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	html += '	public int update(' + getInFuncParams(rows, [createTime]) + ') {\r';
	html += '		Connection conn = DbUtil.getConn("' + dbName + '");\r';
	html += '		StringBuffer sql = new StringBuffer();\r';
	html += '		sql.append("UPDATE ' + table + '");\r';
	html += '		sql.append(" SET ';
	$.each(rows, function(i, item) {
		if (item != null && item != pKey && item.name != createTime)
			html += item.name + ' = ?, ';
	});
	if (html.lastIndexOf(', ') > -1 && html.lastIndexOf(', ') == html.length - 2)
	{
		html = html.substr(0, html.length-2);
	}
	html += '");\r';
	html += '		sql.append(" WHERE ' + pKey.name + ' = ? ");\r';
	html += '		int result = 0;\r';
	html += '		TyStatement pstmt = null;\r';
	html += '		try {\r';
	html += '			pstmt = new TyStatement(conn, sql);\r';
	var s = 0;
	$.each(rows, function(i, item) {
		if (item != null && item != pKey && item.name != createTime) {
			html += '			' + item.getPstmtSet(++s);
		}
	});
	html += '			'+ pKey.getPstmtSet(++s);
	html += '			result = pstmt.executeUpdate();\r';
	html += getDaoFunLast(false, '		');
	html += '		return result;\r';
	html += '	}\r\r';


	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// update one
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	/*
	$.each(rows, function(i, item) {
		if (item != null && item.name != pKey.name && item.name != createTime) {
			html += '	public int update'+ item.upName +'(' + pKey.getFuncParams() + ', ' + item.getFuncParams() + ') {\r';
			html += '		Connection conn = DbUtil.getConn("' + dbName + '");\r';
			html += '		StringBuffer sql = new StringBuffer();\r';
			html += '		sql.append("UPDATE ' + table + '");\r';
			html += '		sql.append(" SET ' + item.name + ' = ? WHERE id = ? ");\r';
			html += '		int result = 0;\r';
			html += '		TyStatement pstmt = null;\r';
			html += '		try {\r';
			html += '			pstmt = new TyStatement(conn, sql);\r';
			html += '			' + item.getPstmtSet(++s);
			html += '			' + pKey.getPstmtSet(++s);
			html += '			result = pstmt.executeUpdate();\r';
			html += getDaoFunLast(false, '		');
			html += '		return result;\r';
			html += '	}\r\r';
		}
	});
	*/

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// delete
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	html += '	public int delete(' + pKey.getFuncParams() + ') {\r';
	html += '		Connection conn = DbUtil.getConn("' + dbName + '");\r';
	html += '		StringBuffer sql = new StringBuffer();\r';
	html += '		sql.append("DELETE FROM ' + table + ' WHERE ' + pKey.name + ' = ? ");\r';
	html += '		int result = 0;\r';
	html += '		TyStatement pstmt = null;\r';
	html += '		try {\r';
	html += '			pstmt = new TyStatement(conn, sql);\r';
	html += '			' + pKey.getPstmtSet(1);
	html += '			result = pstmt.executeUpdate();\r';
	html += getDaoFunLast(false, '		');
	html += '		return result;\r';
	html += '	}\r\r';

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// main
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	html += '	public static void main(String[] args) {\r';
	html += '		' + beanName + 'Dao dao = new ' + beanName + 'Dao();\r';
	html += '		\r';
	html += '		int pageNum = 1;\r';
	html += '		int pageSize = 10;\r';
	$.each(rows, function(i, item) {
		if (item != null && item != pKey) {
			if (item.name == createTime)
			{
				if (item.isKey)
				{
					html += '		' + item.getFuncParams() + ' = '+ this.defValue +';\r';
				}
			} else {
				html += '		' + item.getFuncParams() + ' = '+ this.defValue +';\r';
			}
		}
	});
	html += '		\r';
	html += '		int backId = dao.insert(' + getInParams(rows, [pKey.name, createTime]) + ');\r';
	html += '		print(backId);\r';
	html += '		print(dao.get(backId));\r';
	html += '		print(dao.getList(' + getInParams(keys, [pKey.name], ', ') + 'pageSize, pageNum));\r';
	html += '		print(dao.getCount(' + getInParams(keys, [pKey.name]) + '));\r';
	html += '		print(dao.update(backId, ' + getInParams(rows, [pKey.name, createTime]) + '));\r';
	html += '		print(dao.delete(backId));\r';
	html += '	}\r';

	html += '}';
	return html;

}

里面有用到特殊java类,包括:DbUtil,TyStatement。

这里说明下,DbUtil就是获得DB的连接,关闭连接的函数集合。

TyStatement 这个类有点意思,封装了PreparedStatement,重写了toString函数,输出sql语句和参数,这样可以更快查找问题。后续我会在博客中单独介绍这个类。

这个系列[自动生成代码],主要是把工作中重复工作用工具来自动处理,提高生成效率。

这个只是一个例子,只是抛砖引玉,大家都可以根据自己平时重复工作做个小工具,来提升自我价值。

你可能感兴趣的:(java,sql,自动生成代码,自动分析)