Reputation: 123
Given the following schema,
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String productName;
private String category;
private String vendorName;
// Constructor, getters and setters
}
I would like to find all products
that equals to any pair of category
and vendorName
I have created a class for this
public class FilterRequest {
private String vendorName;
private String category;
// Constructors, getters and setters
}
Ideally the repo should have the following signature,
@Query(---QUERY---)
List<Product> findAllByFilterRequestList(List<FilterRequest> filterRequests);
Any idea how I should approach this? I am thinking of doing this one by one, but it will affect the performance.
Upvotes: 1
Views: 5427
Reputation: 856
You can try to use QueryDSL that uses predicate to filter out the products using the list of FilterRequest
Service
public List<Product> getAllProductsByFilterRequests(List<FilterRequest> filterRequests) {
BooleanBuilder booleanBuilder = new BooleanBuilder();
filterRequests.forEach(
filterRequest -> {
BooleanBuilder booleanBuilder2 = new BooleanBuilder();
booleanBuilder2.and(QProduct.product.category.eq(filterRequest.category));
booleanbuilder2.and(QProduct.product.vendorName.eq(filterRequest.vendorName));
booleanBuilder.or(booleanBuilder2);
}
);
Predicate predicate = booleanBuilder.getValue();
return (List<Product>) productRepository.findAll(predicate);
}
As you can see, booleanBuilder
is the main predicate that aggregates the other predicate booleanBuilder2
. booleanBuilder2
is the one that checks if both vendorName and category values are equal with the product.
Repository
@Repository
public interface ProductRepository extends JpaRepository<Product, Long>, QuerydslPredicateExecutor<Product> {}
Upvotes: 2