Overriding BeanPropertyRowMapper to Support JodaTime DateTime

后端 未结 3 2091
清酒与你
清酒与你 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:19

    The answer of @Sean Patrick Floyd is perfect until you do not have many many custom types.

    Here it a generalized, configurable based on usage extension:

    public class CustomFieldTypeSupportBeanPropertyRowMapper extends BeanPropertyRowMapper {
      private Map, Handler> customTypeMappers = new HashMap, Handler>();
    
      public CustomFieldTypeSupportBeanPropertyRowMapper() {
        super();
      }
    
      public CustomFieldTypeSupportBeanPropertyRowMapper(Class mappedClass, boolean checkFullyPopulated) {
        super(mappedClass, checkFullyPopulated);
      }
    
      public CustomFieldTypeSupportBeanPropertyRowMapper(Class mappedClass) {
        super(mappedClass);
      }
    
      public CustomFieldTypeSupportBeanPropertyRowMapper(Class mappedClass, Map, Handler> customTypeMappers) {
        super(mappedClass);
        this.customTypeMappers = customTypeMappers;
      }
    
      @Override
      protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
        final Class current = pd.getPropertyType();
        if (customTypeMappers.containsKey(current)) {
          return customTypeMappers.get(current).f(rs, index, pd);
        }
        return super.getColumnValue(rs, index, pd);
      }
    
      public void addTypeHandler(Class class1, Handler handler2) {
        customTypeMappers.put(class1, handler2);
      }
    
      public static interface Handler {
        public Object f(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException;
      }
    }
    

提交回复
热议问题