How can i execute sql query like this through Criteria API
and org.springframework.data.jpa.domain.Specification
?
select b.id from brands b
where b.id not in
(select b.id from brands b
left join brand_categories bc on bc.brand_id = b.id
left join categories c on c.id = bc.category_id
where c.id = :id)
I tried this variant, but it didn't work
public static Specification<Brand> notContains(Long id) {
return (root, query, criteriaBuilder) -> {
Subquery<List> subQuery = query.subquery(List.class);
Root<Brand> subRoot = subQuery.from(Brand.class);
Join<Category, Brand> join = root.join("categories");
subQuery.select(subRoot.get("id"));
subQuery.where(criteriaBuilder.equal(join.get("id"), id));
return root.get("id").in(subQuery).not();
};
}
CodePudding user response:
The problem here is that you just mixed up the Root<Brand>
outside and the Root<Brand>
in the sub-select query. This causes a different query to occur and the result is incorrect.
If you change your join
relation in 'subquery' as below, your code will work:
Join<Category, Brand> join = subRoot.join("categories");