GenericVO com.cattsoft.pub.util.ResultSetUtil.convert(ResultSet rs, Class classOfVo) throws Exception
这是这个类最值钱的地方,利用发射原理,以指定vo内得属性的名字,然后把这些名字转为大写,并以”_”连接,这样就成了数据库表的名字。以此把数据库数据拿出。然后装入CenericVO中。其他的方法全都引用这个方法。
/*
* 遍历VO对象,根据VO对象中的属性从ResultSet对象中取同名字段的值
*/
private static GenericVO convert(ResultSet rs, Class classOfVo) throws Exception {
GenericVO vo = null;
vo = (GenericVO) classOfVo.newInstance();
NameConverter nameconverter = NameConverter.getInstance();
Field[] fields = classOfVo.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
String name = nameconverter.convertToDb(field.getName());
String type = field.getType().getName();
try {
if (isTimestamp(type)) {
field.set(vo, rs.getTimestamp(name));
} else if (isDate(type)) {
field.set(vo, rs.getDate(name));
} else if (isBlob(type)) {
field.set(vo, rs.getBlob(name));
} else if (isClob(type)) {
field.set(vo, rs.getClob(name));
} else {
field.set(vo, rs.getString(name));
}
} catch (SQLException e) {
// in most circumstances this exception is ORACLE "invalid column" exception,
// just ignore it.
}
}
return vo;
}
这就不用每次都去自己向bean里set值了,估计会有效率的问题。如果是自动生成的转换方法建议不要修改了,不过自己写的话可以使用这种方法来节省时间。
以下是从属性名字转化成数据库表明的方法:
/**
* convert field names in vo to database column names <br>
* eg. <code>bankBranchId -> BANK_BRANCH_ID</code>
*
* @param voname
* @return
*/
public String convertToDb(String voname) {
String name = "";
ArrayList positions = new ArrayList();
positions.add(new Integer(0));
char[] letters = voname.toCharArray();
for (int i = 0; i < letters.length; i++) {
char letter = letters[i];
if (letter > 64 && letter < 91) { // an uppercase letter
positions.add(new Integer(i));
}
}
positions.add(new Integer(letters.length));
for (int j = 1; j < positions.size(); j++) {
int from = ((Integer) (positions.get(j - 1))).intValue();
int to = ((Integer) (positions.get(j))).intValue();
name += voname.substring(from, to).toUpperCase() + "_";
}
return name.substring(0, name.length() - 1);
}