重写BeanPropertyRowMapper以支持JodaTime DateTime [英] Overriding BeanPropertyRowMapper to Support JodaTime DateTime
问题描述
我的域"对象有几个Joda-Time DateTime
字段.当我使用SimpleJdbcTemplate读取数据库值时:
My Domain object has couple of Joda-Time DateTime
fields. When I'm reading database values using SimpleJdbcTemplate:
患者患者= jdbc.queryForObject(sql,新 BeanPropertyRowMapper(Patient.class),PatientId);
Patient patient = jdbc.queryForObject(sql, new BeanPropertyRowMapper(Patient.class), patientId);
它只是失败了,而且令人惊讶的是,没有错误被记录下来.我想这是因为timestamp
解析为DateTime
在Jdbc中不起作用.
It just fails and surprisingly, no errors were logged. I guess it's because of the timestamp
parsing to DateTime
is not working with Jdbc.
如果可以继承和覆盖BeanPropertyRowMapper
并指示将所有java.sql.Timestamp
和java.sql.Date
转换为DateTime
,那将是不错的选择,并且可以节省很多额外的代码.
If it's possible to inherit and override BeanPropertyRowMapper
and instruct to convert all java.sql.Timestamp
and java.sql.Date
to DateTime
, it would be great and could save a lot of extra code.
有什么建议吗?
推荐答案
正确的做法是将BeanPropertyRowMapper
子类化,覆盖initBeanWrapper(BeanWrapper)
并注册自定义属性编辑器:
The correct thing to do is to subclass BeanPropertyRowMapper
, override initBeanWrapper(BeanWrapper)
and register a custom Property Editor:
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());
}
}
这篇关于重写BeanPropertyRowMapper以支持JodaTime DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!