利用反射构成SQL语句,这样,对于一般表的CURD,都可快速实现。
protected String buildInsertSQL(ResultSetMetaData rsm,DtoInterface dto)
{
String insertSql = null;
try
{
StringBuffer sqlBuf = new StringBuffer(50);
StringBuffer valueBuf = new StringBuffer(50);
sqlBuf.append("insert into ").append(table).append("(");
for(int i=1;i<=rsm.getColumnCount();i++)
{
String methodName = "get" + rsm.getColumnName(i).replaceAll("_", "");
Method method = lookupMethod(dtoClass.getMethods(), methodName);
if(method==null)
{
SysLogger.debug("get" + rsm.getColumnName(i) + " does not exist");
continue;
}
sqlBuf.append(rsm.getColumnName(i)).append(",");
valueBuf.append("'").append(method.invoke(dto)).append("',");
}
sqlBuf.delete(sqlBuf.length() - 1, sqlBuf.length());
valueBuf.delete(valueBuf.length() - 1, valueBuf.length());
sqlBuf.append(")values(").append(valueBuf.toString()).append(")");
insertSql = sqlBuf.toString();
SysLogger.debug(insertSql);
}
catch(Exception e)
{
SysLogger.error("BaseDao.buildInsertSQL()",e);
}
return insertSql;
}
protected String buildUpdateSQL(ResultSetMetaData rsm,DtoInterface dto)
{
String updateSql = null;
try
{
Method getId = lookupMethod(dtoClass.getMethods(),"getId");
if(getId==null)
{
SysLogger.error(dtoClass.getClass().getName() + ":getId method does not exist");
return null;
}
StringBuffer sqlBuf = new StringBuffer(100);
sqlBuf.append("update ").append(table).append(" set ");
for(int i=1;i<=rsm.getColumnCount();i++)
{
if(rsm.getColumnName(i).equals("id")) continue;
String methodName = "get" + rsm.getColumnName(i).replaceAll("_", "");
Method method = lookupMethod(dtoClass.getMethods(), methodName);
if(method==null)
{
SysLogger.debug("get" + rsm.getColumnName(i) + " does not exist");
continue;
}
sqlBuf.append(rsm.getColumnName(i)).append("='");
sqlBuf.append(method.invoke(dto)).append("',");
}
sqlBuf.delete(sqlBuf.length() - 1, sqlBuf.length());
sqlBuf.append(" where id='").append(getId.invoke(dto)).append("'");
updateSql = sqlBuf.toString();
SysLogger.debug(updateSql);
}
catch(Exception e)
{
SysLogger.error("BaseDao.buildUpdateSQL()",e);
}
return updateSql;
}