-
Notifications
You must be signed in to change notification settings - Fork 231
Implementing and using custom converters
Sondre Eikanger Kvalø edited this page Aug 21, 2017
·
8 revisions
If you need to customize a datatype mapping for some reason, you can create your own Mapper implementation
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.
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());
}
}
}
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
Contributing
Documentation
- Configuration
- Fetching data from database
- Fetching data lazily
- Column mappings
- Updates and inserts
- Transactions
- Running queries in a batch
- Integration with Spring Framework
- Register custom converters
- Sql2o on Android
Other resources