When to explicitly exclude Optimistic Locking (Hibernate)?
Under what circumstances would it be appropriate to explicitly exclude optimistic locking from a @OneToMany relationship via Hibernate?
I have been reading a post on Hibernate which basically says any updates to child entities will cause an optimistic lock on parent entity, which is typically unneeded. The key word here is typically... can anyone explain more precisely when you would or would not need optimistic locking on a relationship like this?
Here is the code example given to demonstrate optimistic lock exclusion:
// Bars - these are specifically excluded from optimist lock
// for the object,开发者_JAVA技巧 since we don't want to obtain optimistic
// lock when we add a new bar
@OptimisticLock(excluded = true)
@OneToMany
@JoinColumn(name = "FOO_ID", nullable = false, updatable = false)
private List<FooBar> bars = new LinkedList<FooBar>();
Basically, you need optimistic locking for one-to-many relationships when parent logically "owns" its children, in other words, when parent and children are modified at once as a whole. An Order
consisting of OrderLine
s, which are presented to the user at the same form, can be an example of this kind of relationship.
Otherwise, when children should be modified individually, they should be excluded from optimistic locking. Topic
with Post
s can be an example of this case.
Technically speaking, this question is related to directionality of relationships. The purpose of optimistic locking is to prevent lost modifications, so that you need to enable it for one-to-many relationships when lost modifications are possible. This happens when parent is the owning side of relationship, in other words, when one-to-many relationships are unidirectional (note that it's a natural choice to model relationships such as Order
-OrderLine
).
In the case of bidirectional one-to-many relationships a "many" side is the owning side of the relationship, so that modifications of relationship at the "one" side doesn't affect the database, therefore they can't be lost.
精彩评论