Skip to content

Implementing and using custom converters

Sondre Eikanger Kvalø edited this page Aug 21, 2017 · 8 revisions

Why?

If you need to customize a datatype mapping for some reason, you can create your own Mapper implementation

Example 1: Java 8 LocalDate to/from java.sql.Date

Hint: if you have an updated JDBC driver you don't need to do this by hand as mapping to java.time.LocalDate should work out of the box.

Implementing the org.sql2o.converters.Converter interface

    public class LocalDateConverter implements Converter<LocalDate> {
        @Override
        public LocalDate convert(final Object val) throws ConverterException {
            if (val instanceof java.sql.Date) {
                return ((java.sql.Date) val).toLocalDate();
            } else {
                return null;
            }
        }

        @Override
        public Object toDatabaseParam(final LocalDate val) {
            if (val == null) {
                return null;
            } else {
                return new java.sql.Date(val.atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli());
            }
        }
    }

Add the Converter implementation to NoQuirks

One way of enabling your custom Converter<T> implementation is to add it to your NoQuirks instance upon initialization of Sql2o:

    final Map<Class, Converter> mappers = new HashMap<>();
    mappers.put(LocalDate.class, new LocalDateConverter());
    final Sql2o database = new Sql2o(embeddedDatabaseRule.getDataSource(),
                                     new NoQuirks(mappers));

Your custom Converter implementation will used for converting java.sql.Date to java.time.LocalDate fields