重写BeanPropertyRowMapper以支持JodaTime DateTime

Fir*_*mir 11 java spring spring-jdbc jodatime

My Domain对象有几个Joda-Time DateTime字段.当我使用SimpleJdbcTemplate读取数据库值时:

患者患者= jdbc.queryForObject(sql,new BeanPropertyRowMapper(Patient.class),patientId);

它只是失败,令人惊讶的是,没有记录任何错误.我想这是因为timestamp解析DateTime不适用于Jdbc.

如果可以继承和覆盖BeanPropertyRowMapper并指示转换all java.sql.Timestampjava.sql.Dateto DateTime,那就太棒了,可以节省很多额外的代码.

有什么建议?

Sea*_*oyd 22

正确的做法是子类化BeanPropertyRowMapper,覆盖initBeanWrapper(BeanWrapper)和注册自定义属性编辑器:

public class JodaDateTimeEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(final String text) throws IllegalArgumentException {
        setValue(new DateTime(text)); // date time in ISO8601 format
                                      // (yyyy-MM-ddTHH:mm:ss.SSSZZ)
    }
    @Override
    public void setValue(final Object value) {
        super.setValue(value == null || value instanceof DateTime ? value
                                        : new DateTime(value));
    }
    @Override
    public DateTime getValue() {
        return (DateTime) super.getValue();
    }
    @Override
    public String getAsText() {
        return getValue().toString(); // date time in ISO8601 format
                                      // (yyyy-MM-ddTHH:mm:ss.SSSZZ)
    }
}
public class JodaTimeSavvyBeanPropertyRowMapper<T>
                  extends BeanPropertyRowMapper<T> {
    @Override
    protected void initBeanWrapper(BeanWrapper bw) {
        bw.registerCustomEditor(DateTime.class, new JodaDateTimeEditor());
    }
}
Run Code Online (Sandbox Code Playgroud)