I have two entities called ConfigContainer and Configs. A ConfigContainer can have multiple Configs i.e the association b/w ConfigContainer and Configs is one-to-many.
When the following code inside a method is run:
List<ConfigContainer> doConfigContainerQuery(
ConfigContainerType containerType) {
TypedQuery<DbConfigContainer> query = entityManager.createQuery(
"SELECT cc FROM " +
ConfigContainer.class.getName() +
" cc WHERE cc.configType = :configType", ConfigContainer.class);
query.setParameter("configType", containerType.toString());
return query.getResultList();
}
I see that the Configs are also brought into memory as well even though its fetch type is lazy!
As you can see the Entity which is ConfigContainer gets hydrated with Configs which is at index = 2. Right now this is a dummy environment so the size is only 32 but in a production environment the size of Configs collection can be HUGE!
In our production environment, the above code is a hotspot and gets executed a lot of the times.
We are currently facing performance issues. We found this as one of the culprit.
We are observing this only in our other JPQL queries. Like whenever a JPQL for an entity is executed, the entity gets hydrated with lazy associations.
On the contrary, there is this other scenario where the lazy association is working correctly.
The following is the EntityModel, where entity Foo is associated to ConfigContainer as many-to-one
Foo - (many-to-one) -> ConfigContainer -> (one-to-many) -> Config
When the code called Foo.getConfigsMap()
it first calls configContainer and then the configContainer gets its configs.
The following is the method present in Foo.
getConfigsMaps() {
List<Config> configs = getConfigContainer().getImmutableConfigs(); // <-- breakpoint here.
// some logic
}
If I debug at the above line on the getConfigContainer() part, That time configs are not loaded. See the index = 2
hydratedState = {Object[4] @35594} {
0 = {Long@35249} 33
1 = "configType"
2 = {PersistentSet@35535} Unable to evaluate the expression Method threw 'org.hibernate.LazyInitializationException' exception.
3 = (Long@35396} 11
}
Why is the Entity of ConfigContainer getting hydrated with the lazy collection?
Is there a way to avoid this ?
Hibernate Version: 5.4