问题
I am learning hibernate optimistic lock mechanism and I haven't found answer on my question in user guide
Let's say we have entity like this:
@Entity
class Employee{
@Version
Long versionField;
List<Employee> subordinates;
...
}
And somewhere we have following code:
Employee sub = ....
Emplyee emp = readEmploye();
emp.getSubordinates().add(sub);
Can I control of version incrementation at this case ?
回答1:
By default no. Since you're not changing the entity, but rather other entities that are linked to it.
However it's possible to have that functionality, but it takes quite a bit of configuration and preferably planning in advance. I'm not going to duplicate all the code from the honourable Vlad Mihalcea, see here.
Basically you need to use event listeners to intercept the save calls, and using a RootAware
interface (not a Hibernate interface, just a helper) a child entity being saved knows its "root" and can use the OPTIMISTIC_FORCE_INCREMENT
lock on its parent entity to increase its version.
Regarding data consistency: the flushing can fail if the child was modified or the parent was modified (or both were), but the lock()
on the root entity makes sure that the operation is atomic. If the (pessimistic) lock on the root succeeds, and the (optimistic) lock on the child succeeds, the complete transaction succeeds. Thanks to the pessimistic lock, there's no chance of getting "half updates" that would corrupt the data.
来源:https://stackoverflow.com/questions/58381106/will-hibernate-increment-version-if-i-add-remove-update-element-of-dependable-co