Hibernate + Spring Data JPA: Lazy Loading Across Transaction Boundaries
0 reputation · 29 Apr 2021, 17:37 UTC
Goal: Determine whether a Spring Data JPA repository method that returns an entity with a lazily loaded association should allow safe access to that association after the transaction ends without throwing an exception.
Current behavior: Hibernate throws a LazyInitializationException when the association is accessed outside of an active transaction, unless fetch joins or @Transactional are used. Some developers argue that returning an empty collection (or Optional.empty) would be safer for API consumers, but Hibernate has not settled on a default behavior, leaving the decision as an open design question.
Should Hibernate provide a configuration option to return empty collections (or null) for detached lazily loaded associations instead of throwing LazyInitializationException? What are the performance and correctness implications of enabling hibernate.enable_lazy_load_no_trans for this purpose? How should Spring Data JPA guide users to handle this scenario while maintaining portability across JPA providers?