I’ve been trying to wrap my head around Hibernate for a few days now and I think I’ve hit a corner.
I have an entity with a field annotated as
@ManyToOne and that I initially designed to use a composite
@EmbeddedId. The ManyToOne annotation is unidirectional because the parent would have far too many children to be meaningful in any way.
If I try to persist the entity and I pass its parent (previously fetched in another session) to it, everything works fine - but the parent is fetched again from db before the insert happens. Why is the parent instance fetched from db? (The logs seem to imply that a cached copy could not be found? what does that mean? I passed a copy straight out of storage to it).
In an effort to avoid the additional select, I tried making my entity
Persistable. This made things worse, as the call to persist (via Spring Data JPA’s save) failed with the typical
detached entity passed to persist exception. Surprisingly though, this was on the field annotated with
@ManyToOne! Isn’t there supposed to be no cascading by default on @ManyToOne?!
If id get rid of the
@Embedded id and instead use a standard
@GeneratedValue (strategy = IDENTITY), everything works as expected - and no additional fetches are performed - but now I have one more column in my db!
Can someone point me towards why I am observing this behavior? Thanks!