HQL to find out if a value is in a joined table
I have 2 entity tables (script and tag) and a join table representing many to many relationship. Using the script as the base table, I created an sql statement that allows me to see if a tag is part of a set of tags associated with a single script, and outputs all scripts that have that tag:
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))
)
)
);
Here are the relevant parts of the model used:
@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 (name = "Scripts") public class Script {
@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;
}
}
I need to convert this SQL statement to HQL since I don't have a join table in my model.
+3
source to share
2 answers
The following HQL can help you with this:
SELECT s from Scenario s
JOIN s.tags t
WHERE t.name = :tag
GROUP BY s
HAVING count(t) = 1
Credits from the following site:
http://www.sergiy.ca/how-to-write-many-to-many-search-queries-in-mysql-and-hibernate/
+2
source to share