用于判断值是否在连接表中的HQL

时间:2015-06-05 17:04:50

标签: hibernate hql

我有2个实体表(场景和标签)和一个表示多对多关系的连接表。使用Scenario作为基表,我创建了一个sql语句,允许我查看标记是否是与单个方案关联的标记集的一部分,并输出具有该标记的所有方案:

select count(*)
from scenarios
where scenarios.id not in (
    select tag_to_scenarios.scenarioid
    from tag_to_scenarios
    join tags ON tags.id = tag_to_scenarios.tagid
    where (
        exists( 
            select concat(group_concat(tags.tagname), ',') as tag_list
            from scenarios as sub_scenarios
            left outer join tag_to_scenarios ON tag_to_scenarios.scenarioid = sub_scenarios.id
            join tags ON tags.id = tag_to_scenarios.tagid
            where scenarios.id = sub_scenarios.id
            group by scenarios.id
            having (position('@regression,' in tag_list) = 0))
        )
    )
 );

以下是所用模型的相关部分:

@Entity
@Table(name="tags")
public class Tag {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

public void setId(int id) {
    this.id = id;
}

public int getId() {
    return id;
}

@NotNull
@Column(name = "tagname")
private String tagName;

public void setTagName(String tagName) {
    this.tagName = tagName;
}

public String getTagName() {
    return tagName;
}

}

@Entity

@Table(名称="场景&#34) 公共阶层情景{

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

public int getId() {
    return this.id;
}

public void setId(int id) {
    this.id = id;
}
...
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "tag_to_scenarios",
    joinColumns = {@JoinColumn(name = "scenarioid", nullable = false, updatable = false)},
    inverseJoinColumns = {@JoinColumn(name = "tagid", nullable = false, updatable = false)},
    uniqueConstraints = @UniqueConstraint(name = "scenarioid", columnNames = {"tagid"})
)
private Set<Tag> tags = new HashSet<Tag>(0);

public Set<Tag>  getTags() {
    return this.tags;
}

public void setTags(Set<Tag> tags) {
    this.tags = tags;
}
}

我需要将此SQL语句转换为HQL,因为我的模型中没有连接表。

2 个答案:

答案 0 :(得分:2)

以下HQL可以帮助您实现这一目标:

  SELECT s from Scenario s
    JOIN s.tags t 
   WHERE t.name = :tag 
GROUP BY s 
  HAVING count(t) = 1

积分来自以下网站:

http://www.sergiy.ca/how-to-write-many-to-many-search-queries-in-mysql-and-hibernate/

答案 1 :(得分:1)

老实说,我并不了解您的SQL查询,但如果您只想获得具有给定标志的方案,那么以下HQL查询就足够了:

SELECT s.id FROM Scenario s JOIN tags t WHERE t.tagName = :tagName