我有多个表格:
这些表中的每一个都有一个authorId字段。
我想在sql查询中输出:
MemberId1。 (Nbr of votes + Nbr of Question + Nbr of Answer)
MemberId2。 (Nbr of votes + Nbr of Question + Nbr of Answer)
MemberId3。 (Nbr of votes + Nbr of Question + Nbr of Answer)
如何使用Hibernate标准执行此查询?
在纯SQL中我认为它会是这样的:
select sum(val) from (
select count(*) val from a
union all
select count(*) val from b
union all
select count(*) val from c
union all
select count(*) val from d )
答案 0 :(得分:0)
如果您已在作者和作者中的三个实体之间映射了一对多关系,那么这应该可以解决问题:
Criteria criteria = session.createCriteria(Author.class, "author");
criteria.createAlias("author.votes", "v", Criteria.LEFT_JOIN);
criteria.createAlias("author.questions", "q", Criteria.LEFT_JOIN);
criteria.createAlias("author.answers", "a", Criteria.LEFT_JOIN);
criteria.setProjection(
Projections.projectionList().add(Projections.groupProperty("author.id"))
.add(Projections.countDistinct("v.id"))
.add(Projections.countDistinct("q.id"))
.add(Projections.countDistinct("a.id")));
编辑:
但是由于查询不是动态的,你应该更喜欢HQL,即使在Author中没有关系映射,你也可以编写你的查询:
select author.id, count(distinct(v.id)), count(distinct(q.id)), count(distinct(a.id))
from Author author, Vote v, Question q, Answer a
where v.author.id = author.id
and q.author.id = author.id
and a.author.id = author.id
group by author.id