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...

Sign up to request clarification or add additional context in comments.

5 Comments

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 i updated my answer with something that might be helpful, along the lines of what you are trying...
@toomuchcs Hibernate.initialize only initialises the simple fields, not the relationships...
@Michael Wiles: So how would I initialize another object or collection then?
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.