org.simpleflatmapper.jooq.SfmRecordMapperProvider Maven / Gradle / Ivy
package org.simpleflatmapper.jooq;
import org.jooq.*;
import org.simpleflatmapper.map.SourceMapper;
import org.simpleflatmapper.map.MapperConfig;
import org.simpleflatmapper.map.context.MappingContextFactory;
import org.simpleflatmapper.reflect.ReflectionService;
import org.simpleflatmapper.util.Function;
import java.lang.reflect.Type;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Integration point with jooq.
* Provide a JooqRecordMapper backed by an Sfm {@link org.jooq.Record} {@link SourceMapper}
*/
public class SfmRecordMapperProvider implements RecordMapperProvider {
private final ConcurrentMap mapperCache = new ConcurrentHashMap();
private final Function> mapperConfigFactory;
private final ReflectionService reflectionService;
@Deprecated
/**
* please use SfmRecorMapperProviderFactory.
*/
public SfmRecordMapperProvider() {
this(new Function>() {
@Override
public MapperConfig apply(Type type) {
return MapperConfig.fieldMapperConfig();
}
}, ReflectionService.newInstance());
}
@Deprecated
/**
* please use SfmRecorMapperProviderFactory.
*/
public SfmRecordMapperProvider(
Function> mapperConfigFactory, ReflectionService reflectionService) {
this.mapperConfigFactory = mapperConfigFactory;
this.reflectionService = reflectionService;
}
@Override
public RecordMapper provide(RecordType recordType, Class extends E> type) {
SourceMapper mapper;
MappingContextFactory super Record> mappingContextFactory;
TargetColumnsMapperKey key = getMapperKey(recordType, type);
MapperAndContext mc = mapperCache.get(key);
if (mc == null) {
MapperConfig mapperConfig = mapperConfigFactory.apply(type);
JooqMapperBuilder mapperBuilder =
new JooqMapperBuilder(
reflectionService.getClassMeta(type),
new JooqMappingContextFactoryBuilder(!mapperConfig.unorderedJoin()),
mapperConfig);
int i = 0;
for(Field> field : recordType.fields()) {
mapperBuilder.addField(new JooqFieldKey(field, i++));
}
mapper = mapperBuilder.mapper();
mappingContextFactory = mapperBuilder.contextFactory();
mapperCache.putIfAbsent(key, new MapperAndContext(mapper, mappingContextFactory));
} else {
mapper = (SourceMapper) mc.mapper;
mappingContextFactory = mc.mappingContextFactory;
}
return new JooqRecordMapperWrapper(mapper, mappingContextFactory);
}
private TargetColumnsMapperKey getMapperKey(RecordType recordType, Class> type) {
String[] columns = new String[recordType.size()];
int i = 0;
for(Field> field : recordType.fields()) {
columns[i++] = field.getName();
}
return new TargetColumnsMapperKey(type, columns);
}
private class MapperAndContext {
private final SourceMapper mapper;
private final MappingContextFactory super Record> mappingContextFactory;
private MapperAndContext(SourceMapper mapper, MappingContextFactory super Record> mappingContextFactory) {
this.mapper = mapper;
this.mappingContextFactory = mappingContextFactory;
}
}
}