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

com.github.mikesafonov.specification.builder.starter.predicates.SegmentIntersectionPredicateBuilder 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.annotations.SegmentIntersection;
import com.github.mikesafonov.specification.builder.starter.type.SegmentFilter;
import lombok.RequiredArgsConstructor;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.lang.reflect.Field;

@RequiredArgsConstructor
public class SegmentIntersectionPredicateBuilder implements PredicateBuilder {
    private final Root root;
    private final Field field;
    private final SegmentFilter fieldValue;
    private final SegmentIntersection segmentIntersection;
    private final CriteriaBuilder cb;
    private final ExpressionBuilder expressionBuilder;

    @Override
    public Predicate build() {
        T from = fieldValue.getFrom();
        T to = fieldValue.getTo();

        Expression fromField = expressionBuilder.getExpression(root, field, segmentIntersection.fromField());
        Expression toField = expressionBuilder.getExpression(root, field, segmentIntersection.toField());

        Predicate predicate = cb.and();

        if (from == null && to != null) {
            predicate = new LessThanEqualPredicateBuilder(cb, to, fromField).build();
        } else if (from != null && to == null) {
            predicate = cb.or(
                toField.isNull(),
                new GreaterThanEqualPredicateBuilder(cb, from, toField).build()
            );
        } else if (from != null) {
            predicate =
                cb.or(
                    cb.and(
                        new LessThanEqualPredicateBuilder(cb, from, fromField).build(),
                        cb.or(
                            toField.isNull(),
                            new GreaterThanEqualPredicateBuilder(cb, from, toField).build()
                        )
                    ),
                    cb.and(
                        new GreaterThanEqualPredicateBuilder(cb, from, fromField).build(),
                        new LessThanEqualPredicateBuilder(cb, to, fromField).build()
                    )
                );
        }

        return predicate;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy