Search code examples
postgresqltimestampconvertersvaadindatefield

Vaadin converter for java.sql.Timestamp


I am working with PostgreSQL database and timestamp columns have class java.sql.Timestamp. Even if this class extends java.util.Date, when I edit PopupDateFiels, I obtain error

Unable to convert value of type java.util.Date to model type class java.sql.Timestamp. No converter is set and the types are not compatible.

Default converter factory is unable to work properly. I tried to write

dateField.setConverter(new DateToSqlDateConverter());

or

dateField.setConverter(StringToDateConverter.class);

with the same result.
By clicking on a day in calendar, I can see valid date and time in european format "23.10.2014 13.44", but commit failed with similar messages on console:

Caused by: com.vaadin.data.util.converter.Converter$ConversionException: Could not convert value to Timestamp
at com.vaadin.ui.AbstractField.convertToModel(AbstractField.java:725)
at com.vaadin.ui.AbstractField.getConvertedValue(AbstractField.java:811)
at com.vaadin.ui.AbstractField.commit(AbstractField.java:247)
... 42 more
Caused by: com.vaadin.data.util.converter.Converter$ConversionException: Unable to convert value of type java.util.Date to model type class java.sql.Timestamp. No converter is set and the types are not compatible.
at com.vaadin.data.util.converter.ConverterUtil.convertToModel(ConverterUtil.java:181)
at com.vaadin.ui.AbstractField.convertToModel(AbstractField.java:745)
... 45 more

Where can I get proper converter? Thanks for advice.


Solution

  • I recommend this way:

    PopupDateField pdf = new PopupDateField();
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    ObjectProperty<Timestamp> prop = new ObjectProperty<Timestamp>(ts);
    pdf.setPropertyDataSource(prop);
    pdf.setConverter(MyConverter.INSTANCE);
    

    with this converter:

    public class MyConverter implements Converter<Date, Timestamp> {
    
        private static final long serialVersionUID = 1L;
        public static final MyConverter INSTANCE = new MyConverter();
    
        @Override
        public Timestamp convertToModel(Date value,
                Class<? extends Timestamp> targetType, Locale locale)
                throws ConversionException {
            return value == null ? null : new Timestamp(value.getTime());
        }
    
        @Override
        public Date convertToPresentation(Timestamp value,
                Class<? extends Date> targetType, Locale locale)
                throws ConversionException {
            return new Date(value.getTime());
        }
    
        @Override
        public Class<Timestamp> getModelType() {
            return Timestamp.class;
        }
    
        @Override
        public Class<Date> getPresentationType() {
            return Date.class;
        }
    
        private Object readResolve() {
            return INSTANCE; // preserves singleton property
        }
    
    }