1

我正在尝试使用 Hibernate 重现包含自联接的 SQL 查询。这是 SQL:

select cur.*
  from first ft1,
       first ft2,
       second sc1,
       second sc2,
       third thd
 where sc1.id = sc2.id
   and sc1.idFirst = ft1.id
   and sc2.idFirst = ft2.id
   and ft1.is <> ft2.id    
   and ft1.id = thd.idFirst
   and ft2.id = ?

我尝试使用 Criteria 和 DetachedCriteria 如下,但我无法让它工作:

Criteria criteria = this.getSession().createCriteria(Third.class);

DetachedCriteria first1Criteria = DetachedCriteria.forClass(First.class);
first1Criteria.setProjection(Projections.property("id"));

DetachedCriteria first2Criteria = DetachedCriteria.forClass(First.class);
first2Criteria.setProjection(Projections.property("id"));
first2Criteria.add(Restrictions.eq("id", id)); // where id is passed in from the calling method
first2Criteria.getExecutableCriteria(getSession()).list();

DetachedCriteria second1Criteria = DetachedCriteria.forClass(Second.class);
second1Criteria.setProjection(Projections.property("id"));

DetachedCriteria second2Criteria = DetachedCriteria.forClass(Second.class);
second2Criteria.setProjection(Projections.property("id"));

second1Criteria.add(Property.forName("id.id").in(second2Criteria ));
second1Criteria.add(Property.forName("id.idFirst").in(first1Criteria));
second1Criteria.add(Property.forName("id.idFirst").in(first2Criteria));

first1Criteria.add(Property.forName("id").notIn(first2Criteria));
criteria.add(Property.forName("id").in(first1Criteria));

return criteria.list();

在这种情况下不会引发异常,但实际上并未执行查询。我已经尝试了一些不同的组合,但没有成功。非常感谢任何帮助!

4

0 回答 0