Matching *ALL* items in a list with Hibernate criteria

巧了我就是萌 提交于 2019-12-11 09:26:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!