JdbcTemplate中执行结果包含内嵌式实体

JdbcTemplate中执行结果包含内嵌式实体


当使用JDBCTemplate时会遇到实体中内嵌其他实体的情况,这样实体中字段不会被赋值,提供了三种方式解决这个问题,每种方式各有优缺点
实体

public class User {
    private String name;
    private String password;
    private Father father;
}
class Father {
    private String name;
    private String age;
}

sql

select * from t_user u,t_father f where u.father_id=f.id

java代码

jdbcTemplate.query(sql, paramMap, BeanPropertyRowMapper.newInstance(UserVO.class));

方式一

注意内嵌实体和实体本身有相同的字段会导致值覆盖,根据不同实体需要不同的实现

public class UserRowMapper implements RowMapper<SubstituteDelivery> {
    @Override
    public UserVO mapRow(ResultSet rs, int rowNum) throws SQLException {
        UserVO userVO = (new BeanPropertyRowMapper<>(UserVO.class)).mapRow(rs,rowNum);
        Father father = (new BeanPropertyRowMapper<>(Father.class)).mapRow(rs,rowNum);
        UserVO.setFather(father );
        return userVO ;
    }
}

方式二

列名须和实体字段完全对应(包含下划线大小写都会导致写入失败),通用

public class NestedRowMapper<T> implements RowMapper<T> {
  private Class<T> mappedClass;
  public NestedRowMapper(Class<T> mappedClass) {
    this.mappedClass = mappedClass;
  }
  @Override
  public T mapRow(ResultSet rs, int rowNum) throws SQLException {
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    bw.setAutoGrowNestedPaths(true);
    ResultSetMetaData meta_data = rs.getMetaData();
    int columnCount = meta_data.getColumnCount();
    for (int index = 1; index <= columnCount; index++) {
      try {
        String column = JdbcUtils.lookupColumnName(meta_data, index);
        Object value = JdbcUtils.getResultSetValue(rs, index, Class.forName(meta_data.getColumnClassName(index)));
        bw.setPropertyValue(column, value);
      } catch (TypeMismatchException | NotWritablePropertyException | ClassNotFoundException e) {
         // Ignore
      }
    }
    return mappedObject;
  }
}

方式三

需要顺序,字段多时易混淆

List<UserVO> UserVOS= jdbcTemplate.query("SELECT * FROM message m, user u WHERE u.message_id = m.message_id", new RowMapper<UserVO>() {
    @Override
    public Message mapRow(ResultSet rs, int rowNum) throws SQLException {
        UserVO userVO= new UserVO();
        userVO.setName(rs.getString(1));
        userVO.setPassword(rs.getString(2));

        Father father = new Father();
        father.setName(rs.getString(3));
        father.setAge(rs.getString(4));

        userVO.setFather(father);

        return userVO;
    }
});
上一篇:Vue使用mockjs来生成模拟数据


下一篇:表格从后端下载打开报错的坑