最近没事儿研究了下springMVC,由于不想用hibernate,因此就是用了spring自带的jdbcTemplate。在使用的过程当中发现spring jdbcTemplate须要本身实现将结果集转化为对象的操做,我的感受非常繁琐,因而就使用泛型和反射对这个过程进行了封装,来简化jdbcTemplate的使用。废话少说,上代码: java
public class MyRowMapper<T> implements RowMapper { private Class<T> cls; public MyRowMapper(Class<T> cls) { this.cls = cls; } @Override public Object mapRow(ResultSet rs, int num) throws SQLException { T t = null; try { // 获取对象中的全部字段 Field[] fields = cls.getDeclaredFields(); // 实例化 t = cls.newInstance(); for(Field f : fields){ // if(f.isAnnotationPresent(NotPersistent.class)){ // continue; // } // 获取字段名称 String fieldName = f.getName(); if(StringUtils.isBlank(fieldName)){ continue; } Object o = null; // 经过字段名称获取该字段的值(实体字段名称必须与数据库字段名称一致才能够) o = rs.getObject(fieldName); if(o == null){ continue; } // 使用BeanUtils经过字段名将value设置到实体中 BeanUtils.setProperty(t, fieldName, o); } } catch (Exception e) { e.printStackTrace(); } return t; } }
在这里,我新建了一个类实现了RowMapper接口,并在内部提供了一个带参的构造方法,这样mapRow方法就能够经过全局变量来获取到传进来的Class。 spring
// 使用BeanUtils经过字段名将value设置到实体中 BeanUtils.setProperty(t, fieldName, o);
这里使用BeanUtils而不是PropertyUtils,是由于BeanUtils会对对象类型进行自动转换。 sql
注:实体中若是有多余的字段,即数据表中没有的字段,程序就会报java.sql.SQLException: Column not found异常,在这种状况下,你能够对多余字段进行处理,我在这里是使用注解的方式: 数据库
if(f.isAnnotationPresent(NotPersistent.class)){ continue; }这样,在使用spring jdbcTemplate的时候,就方便多了。好比有个Sort类:
RowMapper rowMapper = new MyRowMapper<Sort>(Sort.class); Sort sort = (Sort) jdbcTemplate.queryForObject(sql.toString(), conditionVals, rowMapper);
这样,就能够获得查询的对象值了。 app
到此结束~若是程序有不妥之处,还望大大们加以指正~ ide
给你们推荐本好书《spring in action》,淘宝上最便宜的哦 this
Spring in Action(第二版)中文版/(美)沃尔斯,(美)布雷登 spa