开发者

Hibernate query count on multiple tabs

I have multiple tables :

  1. vote
  2. Question
  3. Answer

Each of these tables have an authorId field.

I want to output this in an sql query :

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 )

How can I do this query with Hibernate criterias ?

In plain SQL I think it would be like this :

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 )


This should do the trick, provided that you have mapped the one-to-many relationships between authors and the three entities in Author :

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")));

EDIT :

But since the query is not dynamic, you should probably prefer HQL, which would allow you to write your query even if there's no mapping of the relationships in 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜