问题
So I have a Hibernate entity(lets call it Zoos) with a many-to-many relationship set up like this:
@ManyToMany(cascade = {})
@JoinTable(name = "animal",
joinColumns = @JoinColumn(name = "zoo_id"),
inverseJoinColumns = @JoinColumn(name = "animal_id"))
@LazyCollection(LazyCollectionOption.FALSE)
public List<Animal> getAnimal() {
return animals;
}
So now I want to find all zoos with the animals "lions", "tigers", and "bears". Now I don't care if they have other animals or not, but I don't want zoos with only tigers and marmosets. What kind of criteria should I use given a list of animal names to match all elements of the list? If I use Restricions.in I will get zoos that have at least one, but not necessarily all of the animals requested.
Thanks
回答1:
You could use the following query, that I'll let you translate to Criteria:
select zoo from Zoo zoo
where 3 = (select count(distinct animal.name) from Zoo zoo2
join zoo2.animals animal
where zoo2.id = zoo.id
and animal.name in ('lion', 'tiger', 'bear'))
来源:https://stackoverflow.com/questions/18426077/matching-all-items-in-a-list-with-hibernate-criteria