Reputation: 1485
I have a Parent and Child entity. Child has a Manytoone annotation to reference Parent. The use case is that when i load a child by findById
and get the parent out using the getter
. then If I update the parent, I am able to save the parent. I do not want the parent to be updatable which is pulled out from a child.
I want only to update parent if I directly find it by id and change attribute and save.
I know hibernate has no info when i do getParent() from child that it got it from child and not find by id and makes an update to parent.
I tried Immutable annotation on ManytoOne on Parent but it does not prevent an update to be fired.
Is there any way that I can make the parent pulled out from a child non-updatable?
feel free to ask any clarifications.
Upvotes: 2
Views: 4778
Reputation: 22451
You can call EntityManager.detach()
on the parent that you obtain through the getter. Any change made to the detached entity will not be synchronized to the database.
Upvotes: 1
Reputation: 123901
The problem you are experiencing, in fact belongs to the Hibernate Session
. It has nothing with Cascading. Because the session is designed to be a unit-of-work
for us.
Whenever you access an object 1) by ID or 2) by reference, this object is (from that moment) "cached" in the Session
. It is one instance shared accross all the handling during the Session
life-time.
So, once, the Parent
is loaded into session, and you are amending it anyhow, and later Session
is flushed - any changes to Parent
are persisted.
You can call session.evict(parent) explicitly, to avoid changes propagation during the Flush
.
But It seems to me a bit weird, that you are changing the Parent (accidently...maybe) while working with child and not willing to store these changes. Other words, maybe solution is to change the approach.
Upvotes: 3