Overriding BeanPropertyRowMapper to Support JodaTime DateTime

后端 未结 3 2095
清酒与你
清酒与你 2021-02-05 17:55

My Domain object has couple of Joda-Time DateTime fields. When I\'m reading database values using SimpleJdbcTemplate:

Patient patient = jdbc.

3条回答
  •  无人共我
    2021-02-05 18:40

    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
                      extends BeanPropertyRowMapper {
        @Override
        protected void initBeanWrapper(BeanWrapper bw) {
            bw.registerCustomEditor(DateTime.class, new JodaDateTimeEditor());
        }
    }
    

提交回复
热议问题