-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: criteria API: apply projections in outer query and subquery?
PostPosted: Tue Aug 09, 2011 10:13 am 
Newbie

Joined: Tue Aug 09, 2011 9:45 am
Posts: 4
I am using Hibernate 3.3.2.GA with a PostgreSQL database. I have a user_scores table which looks like (irrelevant portions omitted):

Code:
user_scores (
   user_id int,
   type varchar,
   score int
)


I would like to count the number of users of each type with positive, negative, and zero total score. With SQL I would do this like:

Code:
select type, sign_score, count(*) from (select type, user_id, sign(sum(score)) as sign_score from user_scores [where restrictions] group by type, user_id) as _ group by type, sign_score;


However, I am bound to the Criteria API because the application has very complex restriction logic in place of [where condition] in the above query. I would like to avoid duplicating this logic with straight SQL or migrating the application away from the Criteria API.

I understand how to use projections in criteria queries in more typical ways, but does the Criteria API support nesting projections in outer and inner queries like in the SQL query? Alternately, I know that this board isn't for SQL help, but is there any way to rewrite this query without a subquery to be compatible with Hibernate's projections?

Note that I did manage to solve this problem with what appears to be an ugly hack but I would rather use a supported solution. The hack is:

Code:
DetachedCriteria query = ...
query.setProjection(Projections.sqlGroupProjection(
   "type, sign_score, count(*) as results from (" +
      "select {alias}.type, {alias}.user_id, sign(sum({alias}.score)) as sign_score",
      // Hibernate query goes here
      "{alias}.type, {alias}.user_id" +
   ") as _ group by type, sign_score",
   new String[] {"type, sign_score, results"},
   new Type[] {Hibernate.STRING, Hibernate.INTEGER, Hibernate.INTEGER}
));


Thanks!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.