How can I append all the PredicateSpecification or QuerySpecification using JpaSpecificationExecutor in MongoDB with Micronaut data?
Predicate
public class DiscountSpecification {
final static BeanIntrospection<Discount> introspection = BeanIntrospection.getIntrospection(Discount.class);
static String[] discountProperty = introspection.getPropertyNames();
public static PredicateSpecification<Discount> DiscountIdEquals(ObjectId DiscountId) {
return (root, criteriaBuilder) -> criteriaBuilder.equal(root.get(discountProperty[0]), DiscountId);
}
public static PredicateSpecification<Discount> DiscountCodeEquals(String DiscountCode) {
return (root, criteriaBuilder) -> criteriaBuilder.equal(root.get(discountProperty[1]), DiscountCode);
}
}
Now based on the condition I want to append all the predicate
@Introspected
public record QueryBuilderSpecification() {
public static PredicateSpecification<Discount> QueryBuilder(DiscountFilterModel discountFilterModel){
PredicateSpecification<Discount> predicateSpecification = null;
if (discountFilterModel.getId() != null){
predicateSpecification = DiscountIdEquals(new ObjectId(discountFilterModel.getId()));
}
if (discountFilterModel.getDiscountCode() != null){
predicateSpecification = DiscountCodeEquals(discountFilterModel.getDiscountCode());
}
return predicateSpecification;
}
}
The above code doesn't append for both the condition. Quite not sure how to combine both if both are present.
It should be possible to use
DiscountIdEquals(...).and(DiscountCodeEquals(..))
.Your example can be used with
PredicateSpecification.ALL
as the initial state and then have:predicateSpecification = predicateSpecification.and(DiscountIdEquals(...))
.There are some examples in the test apps: https://github.com/micronaut-projects/micronaut-data/blob/master/doc-examples/mongo-example-java/src/test/java/example/PersonRepositorySpec.java#L50