HQL检查对象是否包含请求集合的所有元素
HQL checking if object contains all element s of requested set
我有两个实体。例如,帖子和标签。
我必须编写一个方法,该方法将只接受查询中提到的具有所有标签的帖子。
我试过了
@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
class下一个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 他们:
select t.post from Tag t where t not in (:tagSet) and t.post is not null
而且我们不需要没有任何标签的帖子。让我们也 select 他们:
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)
并且您可以使用命名参数来绑定此查询:
Page<Post> findDistinctByTagsIn(@Param("tagSet") Set<Tag> tagSet, Pageable pageable);
我有两个实体。例如,帖子和标签。 我必须编写一个方法,该方法将只接受查询中提到的具有所有标签的帖子。
我试过了
@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
class下一个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 他们:
select t.post from Tag t where t not in (:tagSet) and t.post is not null
而且我们不需要没有任何标签的帖子。让我们也 select 他们:
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)
并且您可以使用命名参数来绑定此查询:
Page<Post> findDistinctByTagsIn(@Param("tagSet") Set<Tag> tagSet, Pageable pageable);