JOOQ – map a single record using RecordMapper

I am not able to use a RecordMapper mapper to map a single record retrieved via fetchOne/fetchAny.

If I use for example (like in the manual)

List<Something> list =  create.selectFrom(TABLE).fetch().map(mapper);

it works,

but if i use the same mapper for:

Something pojo = create.selectFrom(TABLE).fetchOne().map(mapper);

it doesn’t compile.

Thanks for the help

Answer

This probably has to do with generics. While Result.map() takes a RecordMapper<? super R,E> argument type, Record.map() takes RecordMapper<Record,E>, because Record has no recursive generic type definition for R.

In other words, if you want to reuse the same mapper for both Result.map() and Record.map(), unfortunately, you will need to make it a RecordMapper<Record, E>, which means you’ll lose some of the type safety on the record type.

A workaround would be to create a new result just for the sake of mapping:

Result<TableRecord> result = DSL.using(configuration).newResult(TABLE);
result.add(record);
Something pojo = result.map(mapper).get(0);

Leave a Reply

Your email address will not be published. Required fields are marked *