我有一个User
s的存储库;每个User
都与一个Post
的集合具有OneToMany关系。
如何根据使用JPA规范的帖子数量过滤(和页面)用户存储库?
我最初的尝试看起来像这样:
public static Specification<User> receiptNumberGreaterThanOrEqualTo(int numberToFilterBy) {
return (users, query, cb) -> greaterThanOrEqualTo(cb.count(users.get("posts")), Long.valueOf(numberToFilterBy));
}
但这会导致错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')>=9 limit 100'
这是因为@OneToMany连接需要使用HAVING
子句而不是WHERE
,即select * from users outer left join posts on users.id = posts.id having(count(posts) > someNumber) where user.id = "some-id"
VS
select * from users outer left join posts on users.id = posts.id where user.id = "something" and count(posts) > someNumber;
我可以通过在用户和帖子之间创建连接来生成带有关键字的查询,然后执行以下操作:
query.having(cb.greaterThanOrEqualTo(cb.count(joinOfPosts), Long.valueOf(numberToFilterBy)))
,但其类型为CriteriaQuery
,我不确定如何将其转换为规范。
答案 0 :(得分:2)
我通过在criterionBuilder上使用size()方法解决了这个问题,
即
(users, query, criteriaBuilder) -> criteriaBuilder.greaterThanOrEqualTo(criteriaBuilder.size(users.get("posts")), numberToFilterBy);