2016-02-13 85 views
0

我有两个实体。例如,帖子和标签。 我必须编写一个方法,该方法仅包含查询中提到的具有所有标签的帖子。HQL检查对象是否包含请求集的所有元素s

我试图

@Query("select distinct p from posts p join p.tags t where t in ?1") 
Page<Post> findDistinctByTagsIn(Set<Tag> tagSet, Pageable pageable); 

但是它需要后,如果包含在其标签集标记中的至少一个。

如何仅使用HQL和JPA存储库解决此问题?

UPD:

@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; 
} 
+0

如何帖子和标签链接彼此在数据模型中?我们需要知道这些实体或基础表的相关部分。 –

+0

@MickMnemonic,标签和帖子是一对多的链接 –

回答

1

添加到您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) 

而且你可以使用命名参数来此查询绑定:

Page<Post> findDistinctByTagsIn(@Param("tagSet") Set<Tag> tagSet, Pageable pageable); 
相关问题