我有两个实体。例如,帖子和标签。 我必须编写一个只接受帖子的方法,其中包含查询中提到的所有标签。
我试过了
@Query("select distinct p from posts p join p.tags t where t in ?1")
Page<Post> findDistinctByTagsIn(Set<Tag> tagSet, Pageable pageable);
但是,如果 tagSet 中至少包含一个标签,则需要 Post。
如何仅使用 HQL 和 JPA 存储库解决此问题?
更新:
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "posts_tags", joinColumns = {
@JoinColumn(name = "post_id", nullable = false, updatable = false)},
inverseJoinColumns = {@JoinColumn(name = "tag_id")})
public Set<Tag> getTags() {
return tags;
}
最佳答案
添加到您的Tag
类下一个ManyToOne
关系:
@Entity
public class Tag{
...
private Post post;
@ManyToOne
@JoinTable(name = "posts_tags",
joinColumns = {@JoinColumn(name = "tag_id")},
inverseJoinColumns = {@JoinColumn(name = "post_id")})
public Post getPost(){
return post;
}
...
}
让我们尝试构建查询。
我们不需要带有不在我们的标签列表之外的标签的帖子。我们将在下一个查询中选择它们:
select t.post from Tag t where t not in (:tagSet) and t.post is not null
而且我们不需要根本没有任何标签的帖子。让我们也选择它们:
select p from Post p where p.tags is empty
现在让我们将查询结合在一起:
select p from Post p where
p not in (select t.post from Tag t where t not in (:tagSet) and t.post is not null)
and p not in (select p2 from Post p2 where p2.tags is empty)
您可以使用命名参数来绑定(bind)此查询:
Page<Post> findDistinctByTagsIn(@Param("tagSet") Set<Tag> tagSet, Pageable pageable);
关于java - HQL检查对象是否包含请求集合的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35378299/