Skip to content

Auto POJO mapping

Zsolt Herpai edited this page Aug 7, 2017 · 4 revisions

Automagic POJO result mapping

Select results can be mapped to POJOs automatically - based on object field name/db column name matching. Matching is case-insensitive and ignores '_' characters used particularly often in DB column names.

class Customer {
    private Long id;
    private Instant created;
    private String name;
}
...
ObjectMappers objectMappers = ObjectMappers.builder().build();
...
// should be typically cached - eg as static - since it has some cost to instantiate
private static Mapper<Customer> customerMapper = objectMappers.forClass(Customer.class);

List customers = query.select("SELECT * FROM CUSTOMER").listResult(customerMapper);

Requirements for the POJO
  • Needs a no-arg constructor (can be private - since version 0.9.2).
  • Fields can also be private / final, no need for accessor methods.
  • Field types must be supported by FluentJdbc:
    • jdbc-supported types
    • java.time
    • custom types
Custom type support

Support for custom types - like value objects - can be configured in ObjectMappers builder.

Map<Class, ObjectMapperRsExtractor> extractors = ... 
ObjectMappers.builder()
    .converters(extractors)
    .build();
Example: supporting UUID
ObjectMapperRsExtractor uuidExtractor = (resultSet, i) -> UUID.fromString(resultSet.getString(i));
Map<Class, ObjectMapperRsExtractor> extractors = new HashMap<>();
extractors.put(UUID.class, uuidExtractor);
... // more extractors
ObjectMappers.builder()
    .converters(extractors)
    .build();

Mappers generated by this ObjectMapper will support UUID class in the POJO fields