Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Object Relational Mapping and the fly likes Hibernate lazy fetching strategy Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Hibernate lazy fetching strategy" Watch "Hibernate lazy fetching strategy" New topic

Hibernate lazy fetching strategy

Sebastiaan Kortleven
Ranch Hand

Joined: Mar 12, 2004
Posts: 81
Hi there,

I'm building a Swing application that gets objects from a database using Hibernate.
The user gets a list of all Items in the db. If he chooses an Item he sees a list of all the Bids that are connected to this Item (one-to-many). The Bids are lazy-fetched since there are a lot of Items and the user only needs to see the bids of a few of the Items.

Now I would like to know how to handle the session-side of this story.
I start a session when I load all of the Items, I need to keep this session open since the Bids are lazy fetched. Since it could take ages till the user is done with that session, this is not an option (connection is closed after x seconds). So I need to reattach the Item to a new session, get the Bids and close the session again.

But this implies that I add some hibernate specific code in my GUI logic.. (Items are in a JComboBox, add actionlistener (with the Hibernate session.lock and session.close code), show Items in list).
Is there another (nicer) way so I can keep this code in my db access layer and that I could just call selectedItem.getBids()?
Alexandru Popescu
Ranch Hand

Joined: Jul 12, 2004
Posts: 995
Sebastian I think this is more a design decision than a Hibernate usage scenario. I suggest you to take a look at DAO pattern and also at the patterns related to large collection fetching. They will give an idea how your application should look like.


blog -
Sushil Kumar

Joined: Nov 10, 2004
Posts: 3
A hibernate session can span many connection open and close cycles.
you need to modify your code to "detach" and "reattach" your session object to connections.

Hope this helps
Alexandru Popescu
Ranch Hand

Joined: Jul 12, 2004
Posts: 995
The Hibernate session is in fact a wrapper of a JDBC connection . The detaching/reattaching is about entities.

I agree. Here's the link:
subject: Hibernate lazy fetching strategy
It's not a secret anymore!