[hibernate-dev] JPA merge question about detached entity with lazy fields that haven't been fetched...

Sanne Grinovero sanne at hibernate.org
Wed May 16 11:47:50 EDT 2012

On 16 May 2012 16:15, Scott Marlow <smarlow at redhat.com> wrote:
> On 05/16/2012 11:00 AM, Scott Marlow wrote:
>> On 05/16/2012 10:16 AM, Emmanuel Bernard wrote:
>>> On 16 mai 2012, at 14:28, Scott Marlow wrote:
>>>> According to JPA 2.0 specification section, when merging a
>>>> detached entity with lazy associations that haven't been fetched:
>>>> "
>>>> The persistence provider must not merge fields marked LAZY that have not
>>>> been fetched: it must ignore such fields when merging.
>>>> "
>>>> After merging an entity, will accessing one of the entities LAZY fields
>>>> (that was previously not fetched) result in a lazy initialization error
>>>> or will we try to fetch from the database?
>>> The latter.
>> The latter isn't working for me yet (I get a
>> "LazyInitializationException: failed to lazily initialize a collection
>> of role"), I'll try recreating in a Hibernate ORM test case.
> Steve pointed out that the entity passed into EntityManager.merge() will
> not be attached, instead the merged state is returned and should be
> used.  After I adjusted for that, I can access the lazy field.  :)

that's one of my favourites.
Ignoring the return value of #merge() is an extreme common problem,
I've seen it done by many developers frequently at both trainings and
consulting cases and it often kills the whole JPA experience. I blame
the method name, it's really unexpected it even has a return value.

More information about the hibernate-dev mailing list