-->
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.  [ 2 posts ] 
Author Message
 Post subject: Problem with Hibernate query(join)
PostPosted: Fri Mar 10, 2006 1:23 pm 
Newbie

Joined: Wed Nov 02, 2005 2:03 pm
Posts: 15
I am having two tables Entry and Task.

Entry and Task are having 1 to many relationship.

Now I want to fetch a data from Entry and Task in such a way that in the result
list I get only one row, means all records from Entry table and only one record
from Task table with earliest REG DATE.
for Example:

This is what I am getting result when joining two table.

Name REG DATE
SAM 13-MAR-06
SAM 15-MAR-06

Insteed of this I want just one row
i.e

Name REG DATE
SAM 13-MAR-06


I tried various joins but getting all the records from Task table insteed of just one.

I will appriciate if somebody helps me out.

Thanks.


Top
 Profile  
 
 Post subject: There are several ways to do that, both are slow...
PostPosted: Fri Mar 10, 2006 2:18 pm 
Beginner
Beginner

Joined: Mon Mar 14, 2005 6:07 pm
Posts: 36
You can do this either by (1) running a subquery if your RDBMS supports it, (2) using an "esists," or (3) use group by.

Here are the sketches of how to do that:

1.
Code:
select
    entry e
left join
    e.task t
where
    t.regdate = (select
                     max(tx.regdate)
                 from
                     Task tx
                 where
                     tx.entryid = e.id
                 )

2.
Code:
select
    entry e
left join
    e.task t
where
    not exist = (select
                     tx
                 from
                     Task tx
                 where
                     tx.regdate > t.regdate
                 )

3.
Code:
select
    t.entry.name, max(t.regdate)
from
    Task t
group by
    t.entry.id


The (3) is probably the cleanest and most portable solutuion. If you'd like to retrieve entry itself, not just its name, you'll need to list all fields of the entry in the group by list (this is a limitation, at least in the version that I have). Also listing all entries will not work on Oracle if one of the fields is a BLOB.

I hope this helps.


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

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.