Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding BeanPropertyRowMapper to Support JodaTime DateTime

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

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

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.

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.

Any advice?

like image 530
Firdous Amir Avatar asked Oct 11 '11 18:10

Firdous Amir


1 Answers

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());
    }
}
like image 129
Sean Patrick Floyd Avatar answered Sep 18 '22 15:09

Sean Patrick Floyd