jdbcTemplate查询返回对象的时候,可以自定义rowmapper,也有一个BeanPropertyRowMapper可以用,但要求类属性和表字段严格对应;
如果我们的表字段跟类不能严格对应,这个时候只能写RowMapper,但又不想一个一个写,怎么办?
我们可以通过反射,来动态实现RowMapper
大家可以看到我这个model类,属性和表里的字段是无法映射的,这个时候BeanPropertyRowMapper排不上用场。
只能自定义了
@Table(name = "table_name") public class TableClass implements Serializable { private static final long serialVersionUID = -7355355251303268193L; @Column(name="bizmonth") private String bizMonth; @Column(name="complete_num_1m") private Long completeNum; @Column(name="uncomplete_num_1m") private Long unCompleteNum; @Column(name="total_num_1m") private Long totalNum; }
反射获取RowMapper
/** * 查询表column对应的类field * @param clazz * @return */ public static Map<String, Field> getColumnMap(Class<?> clazz) { Map<String, Field> map = new HashMap<>(); Field[] declaredFields = clazz.getDeclaredFields(); for (Field declaredField : declaredFields) { String fieldName = declaredField.getName(); if (!fieldName.equals("serialVersionUID")) { if (declaredField.isAnnotationPresent(Column.class)) { Column fieldAnnotation = declaredField.getAnnotation(Column.class); String columnName = fieldAnnotation.name(); map.put(columnName, declaredField); } else { throw new NullPointerException("字段缺少Column注解"); } } } return map; } /** * 获取一个类的RowMapper */ public static <T> RowMapper<T> getRowMapper(Class<T> clazz) { Map<String, Field> columnMap = getColumnMap(clazz); RowMapper<T> rowMapper = new RowMapper<T>() { @Override public T mapRow(ResultSet rs, int i) throws SQLException { try { T t = clazz.newInstance(); for (Map.Entry<String, Field> entry : columnMap.entrySet()) { String columnName = entry.getKey(); Field field = entry.getValue(); field.setAccessible(true); Object columnVal = rs.getObject(columnName); field.set(t, columnVal); } return t; } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null; } }; return rowMapper; }
大功告成!