Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
Lazy loading exception with JPAContainer, spring & hibernate
I am trying to test the JPAContainer and struggle with the lazy loading of the data.
I use Spring openEntityManagerInViewFilter and use the @PersistenceContext (type = PersistenceContextType.EXTENDED) to get the EntityManager defined in spring config, but I keep getting lazyInitializationException when I fetch the data into a JPAContainer (relationships are lazyly fetched).
CachingMutableLocalEntityProvider<Depense> depenseProvider = new CachingMutableLocalEntityProvider<Depense>(Depense.class,em); EntityContainer<Depense> depenseCont = new JPAContainer<Depense>(Depense.class); depenseCont.setEntityProvider(depenseProvider); table.setContainerDataSource(depenseCont);
Exception occurs when i set the table datasource.
Anybody already has the container working in a similar setup?
Have you tried setting the entitiesDetached property of the entity provider to false?
Thanks for you reply. I just tried and the Exception persists.
OK. Try to replace the CachingMutableLocalEntityProvider with an ordinary MutableLocalEntityProvider and see what happens.
I just ran some tests and here are the results :
- Still got the LazyInitializationException with a MutableLocalEntityPRovider or LocalEntityProvider or BatchableLocalEntityProvider
- If I inject a LocalEntityProvider as a bean (as taken in the demo example, LocalEntityProviderBean which extends BatchableLocalEntityProvider), it does get rid of the lazyinitializationexception. (EntityManager is injected in the same way with @PersistenceContext annotation)
Apparently the problem seems to be due to how the session is handled by Spring. However, using extended EntityManagers with JPAContainer has not really been tested at all, so if you find a problem that you think is due to a bug in JPAContainer itself, please write a ticket!
Yes that is what I thought. I will do some more tests to have a firmer grasp on the problem and will write a ticket.
As far as I understand the problem might be
- in application architecture - after transaction has been executed your code is still trying to call uninitialized bean. To avoid this you should initialize all lazy initialized beans before transaction has finished either by accessing bean within transaction(it will be initialized automatically) or use join fetch construction in you JPA queries.
- if application architecture looks fine you should sometimes when needed to use join fetch construction to avoid exception
- the last variant when it is too late to change anything you can create DeproxyUtil class that will explicitly re-associate lazy initialized bean with persistent context and deproxy it.
See in separate thread