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

com.github.mikesafonov.specification.builder.starter.predicates.ManyToManyCollectionPredicateBuilder Maven / Gradle / Ivy

There is a newer version: 1.10.0
Show newest version
package com.github.mikesafonov.specification.builder.starter.predicates;

import com.github.mikesafonov.specification.builder.starter.ExpressionBuilder;
import com.github.mikesafonov.specification.builder.starter.FieldWithValue;
import lombok.RequiredArgsConstructor;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * The predicate is constructed according to the following scheme:
 * for each element of the collection a subquery is created that checks the existence of an
 * entry in the intersection table for the link between the related and target table.
 *
 * @param 
 * @author MikeSafonov
 */
@RequiredArgsConstructor
public class ManyToManyCollectionPredicateBuilder implements PredicateBuilder {

    private final Root root;
    private final CriteriaBuilder cb;
    private final CriteriaQuery cq;
    private final FieldWithValue field;
    private final ExpressionBuilder expressionBuilder;

    @Override
    public Predicate build() {
        Collection collection = field.getValueAsCollection();
        List predicates = new ArrayList<>();
        for (Object filter : collection) {
            Subquery sq = cq.subquery((Class) root.getJavaType());
            Root project = sq.from((Class) root.getJavaType());

            Expression expr = expressionBuilder.getExpression(project, field, cb.equal(project, root));
            sq.select(project).where(cb.equal(expr, filter));
            predicates.add(cb.exists(sq));
        }
        return cb.and(predicates.toArray(new Predicate[0]));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy