项目中常常要将数据库中查询出来的记录集转化为JavaBean对象,目前Apache提供的
BeanUtils 和 PropertyUtils 为数据库中字段名与Bean对象中属性名一致的情况提供了
很好的自动化处理方案。但是在实际应用中,数据库中的字段名常常包含了下划线,而在
JavaBean中的属性名一般都去掉了下划线,以字段首字母大写为分隔标记,尤其是在使用了
自动化生成PO对象的工具时,这种情况尤其常见。如果采用 jdbcTemplate 之类的DAO
访问数据库时,Map 与 Bean 的转化就成为了一个难题。
经过思考,本人写了一段可以将数据库中查询出来的Map对象自动转化为对应的PO的
代码,分享如下:
static BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
static{
beanUtilsBean.getConvertUtils().register( new IntegerConverter(null), Integer.class);
beanUtilsBean.getConvertUtils().register(new LongConverter(null), Long.class);
beanUtilsBean.getConvertUtils().register(new DoubleConverter(null), Double.class);
beanUtilsBean.getConvertUtils().register(new StringConverter(null), String.class);
}
public static void map2Bean(Object bean, Map<String, ?> map) {
if (bean == null || map == null)
return;
Field[] fds =bean.getClass().getDeclaredFields();
for (Field des : fds) {
String prop = des.getName();
String key = null;
if ((key = setIgnoreCaseContains(map.keySet(), prop)) != null) {
try {
beanUtilsBean.setProperty(bean, prop, map.get(key));
} catch (IllegalAccessException e) {
logger.error(" Map 转换 Bean失败:", e);
} catch (InvocationTargetException e) {
logger.error(" Map 转换 Bean失败:", e);
}
}
}
}
private static String setIgnoreCaseContains(Set<String> set, String prop) {
for (String str : set) {
if (str.replaceAll("_", "").equalsIgnoreCase(prop)) {
return str;
}
}
return null;
}