Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring & Hibernate: load lazy collection

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

like image 840
toomuchcs Avatar asked Nov 27 '10 18:11

toomuchcs


1 Answers

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

like image 120
hvgotcodes Avatar answered Oct 05 '22 13:10

hvgotcodes