All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.kenshoo.pl.entity.internal.ChildrenIdFetcher Maven / Gradle / Ivy

Go to download

A Java persistence layer based on JOOQ for high performance and business flow support.

There is a newer version: 0.1.121-jooq-3.16.3
Show newest version
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> 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();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy