arbiter
arbiter

Reputation: 29

Hibernate Criteria to match against all child collection

I have a hibernate many to many relationship between Product and Tag
Product class has a 'tags' collection Set as per many to many mapping
I am trying to fetch the products which matches all the tags (not any of the tags)
the following will fetch all products which matches any of the tag.

Criteria crit = session.createCriteria(Product.class,"Prdct");  
   crit.createAlias("Prdct.tags","PT");  
crit.add(Restrictions.in("PT.Name",selectedTags));  
crit.list();  

how to do this using criteria?

Upvotes: 2

Views: 1336

Answers (1)

Firo
Firo

Reputation: 30803

its only useful for sets

// get the count of tags matching the criteria
DetachedCriteria subquery = DetachedCriteria.For(Product.class)
    .add(Expression.eq("id","product.id"))
    .createAlias("tags","tag")  
    .add(Restrictions.in("tag.Name", selectedTags))
    .setProjection(Projections.count("PT.Name"));

// get the Products where there all tags match
Criteria crit = session.createCriteria(Product.class,"product")
    .add(Subqueries.eq(selectedTags.getCount(), subquery);

Upvotes: 1

Related Questions