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 accessing parent of child Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "accessing parent of child" Watch "accessing parent of child" New topic

accessing parent of child

Casey Kcins

Joined: Mar 12, 2007
Posts: 16
So. I'm finally starting to get the hang of Hibernate! There's this thing that's tripping me up though.

I have a Coordinator class which has a one-to-many relationship with a Doctors class. (A Coordinator can be assigned to more then one Doctor). I've successfully created a method that will list all the Doctors for a Coordinator:

but... Doing it to opposite way - list the Coordinator for the Doctor - it doesn't seem to work correctly...

...see, when I originall ran the query, I expected to cast the results as a Coordinator, like so:

...and then return the first item (if exists).
Instead, it throws me an error when I try to Cast the result, so instead I get the id (PK) of the Coordinator, which is the query you see now - and then pass it to another function that will return the Coordinator based on the id.

Is there a reason why I cannot cast the result? I feel it has something to do with the join, but when I try to do doctor.getCoordinator(), it throws a LazyException error. (Which I thought it would)...

So... What *is* the best way to query up?

Thanks for the help!

-- Casey Kcins
David Madouros

Joined: Mar 08, 2005
Posts: 18

I'll take a best guess at the solution to your problem...
To restate your issue: you cannot cast your results into Coordinator objects.

This is happening because you are joining tables explicitly (without fetching). What you get back as your results is a list of Object[] (List<Object[]> . The first element in your array is the Coordinator and the second is the Doctor. From what I can tell, this explicit join is unnecessary for two reasons:

1) Since you are looking for the in the where clause, the keyword 'left' is unnecessary. You will always only get rows bach that have a matching doctor.

2) Hibernate allows you to use implicity joins that traverse the object graph and allow you to use those values in your where clause. Unlike an explicit join, this will only return to you a List of object in your from clause (List<Doctor> .

For example:
Your query will probably give you back what you want if it were coded like this:

David Madouros<br />SCJP 1.4
Casey Kcins

Joined: Mar 12, 2007
Posts: 16
Bam! Thats exactly what I was trying to figure out, and that worked like a charm. Thanks!
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: accessing parent of child