Hibernate Criteria collection property (subquery?)

I am not very familiar with Hibernate Criteria, and apologize if this question is too simple... However, any help is greatly appreciated!

I have two entities, CD and Track. Each CD has collection of Track-objects. In each Track there is a String-field named "title". Now I want to retrieve, using Hibernate Criteria all CDs having a Track with "title" set to a certain value. What I have so far is this:

//session handling
Criteria cdCriteria = session.createCriteria(CD.class);
DetachedCriteria trackCriteria = DetachedCriteria.forClass(Track.class);
trackCriteria.add(Restrictions.eq("title", "SomeTitle"));
trackCriteria.setProjection(Projections.property("title"));
criteria.add(Subqueries.exists(trackCriteria));
List<CD> cds = criteria.list();

This returns all CDs, regardless of track title. Does anybody have any suggestions?

Thank you in advance.


You're very close to the solution. You just missed the restriction stating than the track must be a track of the CD:

Criteria cdCriteria = session.createCriteria(CD.class, "cd");
DetachedCriteria trackCriteria = DetachedCriteria.forClass(Track.class, "track");
trackCriteria.add(Restrictions.eq("track.title", "SomeTitle"));
trackCriteria.add(Restrictions.propertyEq("track.cd.id", "cd.id"));
trackCriteria.setProjection(Projections.property("track.title"));
criteria.add(Subqueries.exists(trackCriteria));
List<CD> cds = criteria.list();

or

Criteria cdCriteria = session.createCriteria(CD.class, "cd");
DetachedCriteria trackCriteria = DetachedCriteria.forClass(Track.class, "track");
trackCriteria.add(Restrictions.eq("track.title", "SomeTitle"));
trackCriteria.createAlias("track.cd", "trackCd");
trackCriteria.add(Restrictions.propertyEq("trackCd.id", "cd.id"));
trackCriteria.setProjection(Projections.property("track.title"));
criteria.add(Subqueries.exists(trackCriteria));
List<CD> cds = criteria.list();

You could also avoid the subquery and simply use a join

Criteria cdCriteria = session.createCriteria(CD.class, "cd");
criteria.createAlias("cd.tracks", "track");
criteria.add(Restrictions.eq("track.title", "someTitle"));
criteria.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

You can do this actually without the join - simply use cdCriteria.getAlias() place of the string value of the alias. Thus, the key line would be:

trackCriteria.add(Restrictions.propertyEq("trackCd.id", cdCriteria.getAlias() + ".id"));
链接地址: http://www.djcxy.com/p/36982.html

上一篇: 限制包括一个小组

下一篇: Hibernate Criteria集合属性(子查询?)