reset password
Author Message
Vanquish39
Posts: 134
Posted 21:58 Oct 21, 2011 |

Professor, how can I eagerly load a collection without specifying a jpa annotation such as FetchType="eager".

Let's say I have a customer class and it has a list of accounts.  I want to query all the customers and I want the accounts loaded also.  I would use like.... select c from Customer c join c.accounts a...  If a session is open, I'm sure the accounts load, but if a session is closed... it doesn't load.  I saw some examples specifying ... select c from Customer c join  fetch c.accounts a


Any recommendations?  Thanks

cysun
Posts: 2935
Posted 23:56 Oct 21, 2011 |

It should be

select c from Customer c left join fetch c.accounts

a) The difference between join and join fetch is that join returns both objects, while join fetch returns only the main object (with the collection loaded of course).

b) You should do a left join fetch to include the customers who do not have any account.

c) FetchType.EAGER only works when you load an object by id. If the object(s) is loaded through a query, you'll have to use join fetch to "eagerly" load a collection.

There's an example in CSNS2. Check out the getUserByUsername() method in UserDaoImpl.