使用Spring JdbcTemplate查询出数据以后,默认返回的是Map,列名为key,值为value,为了方便操作自然要转换到我们的JavaBean实体对象,spring也提供了一个常规的通用操作类和方法,BeanPropertyRowMapper.newInstance(entityClazz),可以完成一般的转换,前提是表的列名和类的属性名必须一致,下划线分隔的貌似也行,没有进行测试。但前面提到我表中的列名为了防止冲突,都是以“_”开头的,并且以“_”分隔,在实际运行中发现BeanPropertyRowMapper并不能完成转换,没办法只能自己实现一个了。同样用到了Java的反射和名称的转换,原理上和构建sql时是差不多的。要实现自定义的转换必须实现spring提供的RowMapper <T>接口,下面是代码:
/** * 默认通用类型映射转换 * * User: liyd * Date: 2/12/14 * Time: 10:02 PM */ public class DefaultRowMapper implements RowMapper<Object> { /** 转换的目标对象 */ private Class<?> clazz; /** 名称处理器 */ private NameHandler nameHandler; public DefaultRowMapper(Class<?> clazz, NameHandler nameHandler) { this.clazz = clazz; this.nameHandler = nameHandler; } @Override public Object mapRow(ResultSet resultSet, int i) throws SQLException { Object entity = ClassUtils.newInstance(this.clazz); BeanInfo beanInfo = ClassUtils.getSelfBeanInfo(this.clazz); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { String column = nameHandler.getColumnName(pd.getName()); Method writeMethod = pd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } try { writeMethod.invoke(entity, resultSet.getObject(column)); } catch (Exception e) { throw new MincoderException(e); } } return entity; } }
这样就大功告成了,想不到一点点内容写出来也有这么多,可能是我总结的不好吧。