There are always so many questions related to issues with detached entities!
First, they often cause LazyInitializationException
in Hibernate.
Yes, there are another persistence providers, which don't throw exceptions,
but I think that they have some problems with consistency.
Consider we have A
and B
entities that there is reference
(@ManyToOne
) from A
to B
that is required to be non-null.
We started our session, loaded A
instance and then closed session.
After that we try to obtain a reference to B
.
And assume that another transaction just deleted both our A
and B
instances. So when we query from database we can't find appropriate B
instance and get null
!
So our contract is violated. Some code that relies on fact that
a.getB()
returns an object will throw an NullPointerException
.
With persistent entities this is impossible because we have all lazy
loading in the same transaction with obtaining object itself,
so all operations are atomic (if we have a proper transaction isolation of course).
Also there are problems when you want to store persistent and detached entities in one Set
. It that case you should always override equals
and hashCode
, which usually looks awkward, as I can't see a really good way to do it.
To get a detached entity back into EntityManager
you should use merge
which is glitchy.
So my question is: is there is a reasonable scenario where detached entities are really needed? Furthermore, when do you have to mix detached and persistent entities
and merge detached entities into a new EntityManager
?