6

How do you explicitely load a lazy Object/collection? So far I've found the only way to do this is to explicitely ask for a getter/setter of the object while it is still attached to the session: ie

List < Account > accounts = Bank.getAccounts();
accounts.get(i).getAccountNumber();

Is there another less dodgy way to do this?

I work with Spring btw, so depending on what service is being called, I want to load different collections/obkjects

1 Answer 1

13

I dont think the way you are doing it is dodgy; the goal of hibernate is to be transparent.

However, there are alternatives:

1) If you want to always load the collection, you can just make the collection not lazy in the configuration. Beware loading too much data...

2) If you want to sometimes load the collection, then leave lazy=true and add another DAO method

loadBankWithAccounts()

and either do what you are doing, with a comment about why you are initializing the collection, or use a HQL query with fetch. Check out the documentation.

3) Check out section 19.1.4 of the hibernate documentation, which describes how to use something like

Hibernate.initialize(bank.getAccounts())

which allows you to be more explicit with your collection initialization...

5
  • just found that there is something like Hibernate.initialize(proxy Obj), but it doesn't seem to work. where the problem occurs is with a 1-1 relation. I just do Hibernate.initialize(leerling.getFoto())
    – toomuchcs
    Commented Nov 27, 2010 at 19:12
  • @toomuchcs i updated my answer with something that might be helpful, along the lines of what you are trying...
    – hvgotcodes
    Commented Nov 27, 2010 at 19:24
  • @toomuchcs Hibernate.initialize only initialises the simple fields, not the relationships... Commented Nov 29, 2010 at 11:14
  • @Michael Wiles: So how would I initialize another object or collection then?
    – toomuchcs
    Commented Nov 29, 2010 at 22:17
  • like you showed in your question calling the get on the relationships. It's the same thing as an "initialise" would do in any case. That's what I've always done - works. Commented Dec 2, 2010 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.