File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Correlated Subquery in Hibernate Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Correlated Subquery in Hibernate" Watch "Correlated Subquery in Hibernate" New topic

Correlated Subquery in Hibernate

Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
I'm working on converting a fairly hairy SQL query into HQL and running into some trouble. I was hoping someone else would be able to shed some light on the problem.

Here's the original SQL query:

Notice that the pl.prevID in the subquery is related to the alias pl defined in the outer query.

The purpose of this query is to generate a list of all rows in the PrevLevels table and, for each row, get the number of records in the CRev table that correspond. So, for example, I might see something like this:

Here's what I have in HQL:

I can get the outer query to work without the subquery and, likewise, I can get the subquery to work without the outer query, but if I try to execute this query as is, I get this error message:

It then goes on to spit out the query I just wrote above.

Any bright ideas?

SCJP Tipline, etc.
Edvins Reisons
Ranch Hand

Joined: Dec 11, 2006
Posts: 364
Not that I would call it bright , but could it be that this "aggregate function" confusion comes from the parentheses around the inner SELECT?
Craig Taylor
Ranch Hand

Joined: Jul 17, 2008
Posts: 64
Can you rewrite as :

I've always ran into problems with hibernate and multi selects (eg: select x,y, (select z) ) - I usually have to rewrite as a group...
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by Craig Taylor:
Can you rewrite as :

Unfortunately, no - the two queries are not the same. The query you have here (which is actually what I had started with) will leave out rows from the table PrevLevels if there are no matching records in the other tables. For my use, it's very important that, if there are no matching rows, I still get that row back with a value of 0.
Rodrigo Lopes
Ranch Hand

Joined: Feb 29, 2008
Posts: 119
Have you tried with left (outer) join?

Don't get me started about those stupid light bulbs.
subject: Correlated Subquery in Hibernate
Similar Threads
JOIN syntax for HQL . Need help!
HQL query hibernate
count(*) vs count(id)
any good hql query for this scenario?
SQL injection?