简体   繁体   中英

Hibernate Restriction criteria to match from a collection property

I have a entity with a @ElementCollection field using hibernate eg:

@ElementCollection(fetch = FetchType.EAGER)
@Column(name="years")
private Set<Integer> years = new HashSet<>();

where years is a set of years, I want to only filter those records which contain the particular queryYear in that set of years.

What kind of Restriction criteria can I use in Hibernate as Restriction.in doesn't work vice versa

You cannot do this in one criteria, since this cannot be done also in one normal query without using some syntax like HAVING , or using multiple join or other tricky workaround.

The closest criteria is using Restrictions.in then using agregate to count the row number, something like this:

c.add(Restrictions.in("years", years));
c.setProjection(Projections.projectionList()
    .add(Projections.groupProperty("id"))
    .add(Projections.count("id")));

All the result that have count = years.size is the id that you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM