com.kenshoo.pl.entity.internal.ChildrenIdFetcher Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of persistence-layer Show documentation
Show all versions of persistence-layer Show documentation
A Java persistence layer based on JOOQ for high performance and business flow support.
package com.kenshoo.pl.entity.internal;
import com.google.common.collect.Iterables;
import com.kenshoo.jooq.DataTable;
import com.kenshoo.jooq.QueryExtension;
import com.kenshoo.pl.entity.UniqueKey;
import com.kenshoo.pl.entity.*;
import com.kenshoo.pl.entity.internal.fetch.QueryBuilder;
import org.jooq.*;
import org.jooq.impl.DSL;
import org.jooq.lambda.Seq;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.jooq.lambda.Seq.seq;
public class ChildrenIdFetcher, CHILD extends EntityType> {
private final PLContext plContext;
public ChildrenIdFetcher(PLContext plContext) {
this.plContext = plContext;
}
public Stream>
fetch(Collection extends Identifier> parentIds, UniqueKey childKey) {
if (parentIds.isEmpty()) {
return Stream.empty();
}
final PARENT parentType = first(parentIds).getUniqueKey().getEntityType();
final CHILD childType = childKey.getEntityType();
final EntityType.ForeignKey keyToParent = childType.getKeyTo(parentType);
final UniqueKey parentKey = first(parentIds).getUniqueKey();
final UniqueKey childFK = new UniqueKey<>(keyToParent.from());
final EntityField, ?>[] requestedFields = Iterables.toArray(Seq.concat(
Seq.of(parentKey.getFields()),
Seq.of(childKey.getFields()),
Seq.of(childFK.getFields())), EntityField.class);
List entities = plContext.select(requestedFields)
.from(childType)
.where(PLCondition.trueCondition())
.fetchByKeys(parentIds);
return fullIdentifierOf(entities, parentKey, childKey, childFK);
}
private Stream> fullIdentifierOf(List entities, UniqueKey parentKey, UniqueKey childKey, UniqueKey childFK) {
return seq(entities)
.map(entity ->
new FullIdentifier<>(
parse(parentKey, entity),
parse(childKey, entity),
parse(childFK, entity)
));
}
private > Identifier parse(UniqueKey key, CurrentEntityState entity) {
final Object[] ids = Seq.of(key.getFields())
.map(entity::get)
.toArray();
return new UniqueKeyValue<>(key, ids);
}
private T first(Collection collection) {
return collection.iterator().next();
}
}