LazyInitializationException when accessing lazy association after Hibernate Session.close()
0 reputation · 20 Apr 2024, 21:38 UTC
The goal is to return entity data from a public REST endpoint without accidentally initializing uninitialized Hibernate proxies or exposing associations outside the transaction that loaded them.
Hibernate throws LazyInitializationException when a lazy association is accessed after its Session is closed. Setting hibernate.enable_lazy_load_no_trans permits loading outside a transaction, but it does not restore transactional isolation and may issue additional SQL unexpectedly. Serializing a managed entity directly in an HTTP response can trigger proxy initialization during serialization, which may cause failures or unintended database reads. Behavior may differ between Hibernate 5.x and 6.x; confirm against the target version.
Should the application rely on hibernate.enable_lazy_load_no_trans to allow post-close access, or is a DTO projection required to control serialization? Does JSON serialization of an entity with uninitialized proxies risk accidental data exposure after the Session is closed?