将参数传递给mapRow

时间:2018-02-09 09:23:59

标签: java jdbc spring-jdbc jdbctemplate

我需要将参数传递给我的RowMapper,因为我需要将时区应用于日期字段。目前这是我的代码:

查询:

@Override
    public List<GCProjectMember> selectGCMembers(Long jobId,String timezone) {

        DataSource dataSource = DataSourceBeanBuilder.getClientDataSource(ClientContextHolder.getCustomerType(),
                this.getClass().getName());
        this.setDataSource(dataSource);

        List<GCProjectMember> membersList = getJdbcTemplate().query(SELECT_GC_MEMBERS, new Object[] { jobId },
                new GCProjectMemberRowMapper());
        if (membersList.size() > 0) {
            return membersList;
        } else {
            return Collections.emptyList();
        }
    }

的RowMapper:

public class GCProjectMemberRowMapper extends BasicRowMapper implements RowMapper<GCProjectMember> {

    @Override
    public GCProjectMember mapRow(ResultSet rs, int rowNum) throws SQLException {
        GCProjectMember member = new GCProjectMember();
        ...
        if (hasColumn(rs, "sign_date")) {
            member.setSignDate(rs.getTimestamp("sign_date"));
        }

        ....
        return member;
    }

}

如何将时区从查询传递到rowmapper?

1 个答案:

答案 0 :(得分:3)

您可以在GCProjectMemberRowMapper中创建参数化构造函数,并在初始化对象时将时区值传递给它。

public class GCProjectMemberRowMapper extends BasicRowMapper implements RowMapper<GCProjectMember> {

   private TimeZone timezone;

   public GCProjectMemberRowMapper(TimeZone timezone) {
     this.timezone = timezone
   }
   @Override
   public GCProjectMember mapRow(ResultSet rs, int rowNum) throws SQLException {
    GCProjectMember member = new GCProjectMember();
    ...
    if (hasColumn(rs, "sign_date")) {
        member.setSignDate(rs.getTimestamp("sign_date"));
    }
    // use timezone here
    ....
    return member;
}

可以像这样更改调用代码。

@Override
public List<GCProjectMember> selectGCMembers(Long jobId,String timezone) {

    DataSource dataSource = DataSourceBeanBuilder.getClientDataSource(ClientContextHolder.getCustomerType(),
            this.getClass().getName());
    this.setDataSource(dataSource);

    List<GCProjectMember> membersList = getJdbcTemplate().query(SELECT_GC_MEMBERS, new Object[] { jobId },
            new GCProjectMemberRowMapper(timezone));
    if (membersList.size() > 0) {
        return membersList;
    } else {
        return Collections.emptyList();
    }
}