添加子表的计数以从具有hibernate条件API的父项中进行选择

时间:2015-10-26 22:12:27

标签: java sql hibernate hibernate-criteria

如何使用Hibernate Criteria API执行此SQL查询?

SELECT c.*, count(r.id) FROM COURSE c left join REFERRAL r on c.id = r.course_id group by c.id

1 个答案:

答案 0 :(得分:0)

这样的事情似乎足够接近:

Criteria criteria = currentSession().createCriteria(Referral.class, "r");
criteria.createAlias("r.course", "course");

ProjectionList projections = Projections.projectionList();
projections.add(Projections.groupProperty("course.id"));
projections.add(Projections.count("r.id"));

return list(criteria
        .setProjection(projections));