我对Hibernate Criteria不是很熟悉,如果这个问题太简单,请道歉......但是,非常感谢任何帮助!
我有两个实体,CD和Track。每张CD都有Track-objects的集合。在每个Track中都有一个名为“title”的字符串字段。现在我想使用Hibernate Criteria检索所有CD,其中“title”设置为某个值。到目前为止我所拥有的是:
//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();
无论曲目标题如何,都会返回所有CD。有人有什么建议吗?
提前谢谢。
答案 0 :(得分:9)
您非常接近解决方案。你刚刚错过了限制声明而不是曲目必须是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();
或
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();
您还可以避免使用子查询,只需使用连接
Criteria cdCriteria = session.createCriteria(CD.class, "cd");
criteria.createAlias("cd.tracks", "track");
criteria.add(Restrictions.eq("track.title", "someTitle"));
criteria.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);
答案 1 :(得分:0)
您可以在没有连接的情况下实际执行此操作 - 只需使用别名的字符串值的cdCriteria.getAlias()。因此,关键线将是:
trackCriteria.add(Restrictions.propertyEq("trackCd.id", cdCriteria.getAlias() + ".id"));