2008年5月15日 星期四

使用beanutil


有一次寫一個小小的系統.
就有遇到要一直從DB撈資料塞到java bean 裡.
就要寫一大堆setter ,
分享一個小小程式,可以自動對應欄位和bean properties,
不過就在table 的欄位名稱和bean 的attribute 要取一樣的名字

例如:

tableA.ID
talbleA.CHINESE_NAME
talbleA.EMAIL

bean.id
bean.chineseName
bean.email

protected Object setBeanProperty(Object bean, ResultSet rs) {
String[] columns = getColumnName(rs);
try {
for (int i = 0; i < columns.length; i++) {
String str = determineClassType(rs.getObject(i + 1));
BeanUtils.setProperty(bean, columns[i], str);
}
} catch (Exception e) {
throw new DAOException(e, "Bean property conversion failed!");
}
return bean;
}

/**
* get all column name.
*
* @param ResultSet
* @return String []
* @author kenny
*/
protected String[] getColumnName(ResultSet rs) {

int columnCount = 0;
ResultSetMetaData metaData = null;
String columns[] = null;

try {
metaData = rs.getMetaData();
columnCount = metaData.getColumnCount();
columns = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
StringBuffer sb = new StringBuffer(metaData
.getColumnName(i + 1).toLowerCase());
int index = index = sb.indexOf("_");
;
while (index != -1) {

String tmp = sb.substring(index + 1, index + 2)
.toUpperCase();

sb.replace(index + 1, index + 2, tmp);
sb.deleteCharAt(index);
index = sb.indexOf("_");

}

columns[i] = sb.toString();
}
} catch (Exception e) {
logger.error("error at getColumnName:" + e.getMessage(), e);
}

return columns;
}

/**
*
* @param Object
*
* @author kenny
*/
private String determineClassType(Object o) {
String rtn = null;
if (o instanceof String) {
rtn = Util.dataBlank(o);
} else if (o instanceof java.sql.Timestamp ) {
long l = ((java.sql.Timestamp) o).getTime();
Date d = new Date(l);
rtn = Util.commonDateFormat(d, "yyyy/MM/dd HH:mm");
} else if (o instanceof java.util.Date) {
rtn = Util.commonDateFormat((java.util.Date) o, "yyyy/MM/dd");
}else if (o instanceof java.lang.Number) {
rtn = o.toString();
}else if(o == null){
rtn="";
} else {
rtn = o.toString();
}
return rtn;
}

沒有留言: