我需要编写一个JPQL查询,它返回包含所有列出的标签的元素

时间:2015-06-25 20:51:24

标签: java sql spring-data-jpa jpql

我有两个实体

`@Entity @Table(name =“quiz_questions”) 公共课QuizQuestion {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonView(ShortSummary.class)
private Long id;

@Column(name = "title", nullable = false)
@JsonView(ShortSummary.class)
private String title;

@Column(name = "text", nullable = false, length = 4096)
@JsonView(ShortSummary.class)
private String text;

 /**
 * List of tags, which include the question
 */
@JoinTable(name = "quiz_questions_tags",
joinColumns = @JoinColumn(name = "quiz_question_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id"))
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.REFRESH,   CascadeType.MERGE}) // do not add PERSIST
@JsonView(ShortSummary.class)
private Set<Tag> tags;

} ` 和

`@Entity @Table(name =“tags”) public class Tag实现Serializable {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@Column(name = "tag")
private String tag;

}`

我需要编写一个查询,返回所有这些标记的问题列表。 在存储库中我有方法

 @Query("SELECT DISTINCT q FROM QuizQuestion q JOIN q.tags u WHERE u IN :tags  ") // working, but the output even if one tag is associated with the question
   List<QuizQuestion> findTag (@Param("tags") Set<Tag> tags);

我不知道如何正确地写这个请求。救救我!

1 个答案:

答案 0 :(得分:0)

您可以使用类似

的内容
select q from QuizQuestion q where (
    select count(tag.id) 
    from QuizQuestion q2 
    inner join q2.tags tag 
    where q2.id = q.id
    and tag.id in :requiredTagIds) 
= :requiredTagCount

其中requiredTagIds是所需标记的ID集合,requiredTagCount是此集合的大小。