In my web application I have an Object with a OneToMany relationship with Child.
When selecting my Objects I execute the following query:
from Object o
and then i should print for every object how many children it has with
// Foreach
object.children.size()
Assuming the object has a lot of children (let’s say 30’000);
Is it a waste of resources calling size() or the ORM framework (in my case Hibernate) will take care of that without loading all the children?
Using JPA (the standard):
Entity.getCollection().size()would trigger lazy loading to retrieve all of the child collection – so yes, it would be fairly slow, unless you needed to operate on all/most elements anyway. Note: for all (sane) implementations of JPA, this will NOT issue 30,000 seperate queries – it will issue one query that returns 30,000 rows in the result set.@OneToMany(fetch=FetchType.EAGER)EntityManager.getQuery()/getTypedQuery()/getNamedQuery()(or even SQL viagetNativeQUery()). This is quite simple and highly performant:You can enable level 2 caching. JPA Caching Summary
To statically configure level 2 caching:
Then mark which entities should be automatically cached in the level 2 cache:
Using Proprietary approach (e.g. Hibernate “Extra-Lazy” collections):