Recently I enabled bytecode enhancement in an application using hibernate 5.2.17.Final (via maven plugin) .
The only option I use is <enableLazyInitialization>true</enableLazyInitialization> .
After that I noticed an unexpected LazyInitializationException in code that was working fine before the change .
Based on https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/chapters/pc/BytecodeEnhancement.html I added @LazyToOne(LazyToOneOption.NO_PROXY) on one ManyToOne relationship
This made lazy loading work but now if some code loads the entity without initializing this relationship, passes entity ouside of session scope and then tries to merge it in another session then it ends up with :
org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [classname] - no session and settings disallow loading outside the Session
Which is a bit weird because the same code without @LazyToOne and bytecode instrumentation returns both entities .
Is this issue known/documented ?
This lazy load exception is triggered by CascadeType.MERGE set in @ManyToOne annotation .
I reproduced the issue with code fetched from latest master and will submit a pull request in a moment .
, thanks for the test case.
This is definitely a bug. Hibernate should not be trying to initialize a property on a detached entity.
In 4.2, when the merge operation cascades to the lazy association here, the value extracted from the entity by persister.getPropertyValue( parent, i ) is null, not an initialized value. As a result, cascadeProperty() does nothing. I believe that is the correct behavior for a bytecode-enhanced lazy *-to-one association.
If the association being merged was an uninitialized proxy instead, Hibernate would merge that proxy by simply loading an uninitialized proxy without initializing it and adding it to the PersistenceContext.
The corresponding code in master is here. You can see that Hibernate explicitly loads the lazy association in the detached entity, which is incorrect.