If you would like to start optimizing performance, you can ask Hibernate to fetch the associated objects and collections for an object in one query. If we were lazy loading with Hibernate, the objects would not be initialized until we accessed them. If we use fetch on a join in our query, we can ask Hibernate to retrieve the objects in the collection at the time the query executes. Add the fetch keyword after the join in the query:
When you use fetch for a query like this, Hibernate will return only Supplier objects, not the Product objects. This is because you are specifying the join so Hibernate knows which objects to fetch (instead of lazy loading). If you need to get the Product objects, access them through the associated Supplier object. You cannot use the properties of the Product objects in expressions in the where clause, for instance. Use of the fetch keyword overrides any settings you have in the mappings file for object initialization.
So what I understand from this excerpt is that:
1. "If we use fetch on a join in our query, we can ask Hibernate to retrieve the objects in the collection at the time the query executes"
AND at the same time
2. "When you use fetch for a query like this, Hibernate will return only Supplier objects, not the Product objects"
My Question: Am I the only one who sees the contradiction between these assertions?
OK, I had to read it a few times to see what they were saying too. What they mean is that you get a List of Supplier objects returned with each Supplier object's collection of Products being fully populated.
As opposed to a List of Product objects being returned.
Basically you can only do
List<Supplier> = query.list();
you cannot do
List<Product> = query.list();
In the List<Supplier> each supplier will have all their related products in there.
Thanks, I thought it would return a List of Object arrays, each array consists of a pair of a Supplier Object and a Product object.
I think that is what that should have returned if I had used simply join, without the fetch keyword. A List of arrays of a Supplier Object and a Product proxy. So I would expect the fetch simply exchange the Product proxy with a Product populated Object. Actually, it's quite hard for me to guess what is exactly going to be returned.