我有一个具有乐观锁机制的实体Person。一个人有几个手指。如果任何一个手指改变,我希望Person的乐观锁定计数器计数。
@Test
public void testVersionUpOnChildChange() throws Exception {
// persist entities => version is initially created
doInTransaction(new HibernateMethod() {
@Override
public void run(Session session) {
michael = new Person("Michael");
michael.setId(1);
michael.addFinger(new Finger("Thumb", michael));
michael.addFinger(new Finger("Ringfinger", michael));
michael.addFinger(new Finger("Index", michael));
session.persist(michael);
}
});
Assert.assertEquals(0, michael.getVersion().intValue());
// just read michael from database => michaels version counter should stay as it is
doInTransaction(new HibernateMethod() {
@Override
public void run(Session session) {
michael = (Person) session.get(Person.class, 1);
session.update(michael);
}
});
Assert.assertEquals(0, michael.getVersion().intValue());
// do changes to michael directly => version counter goes up
doInTransaction(new HibernateMethod() {
@Override
public void run(Session session) {
michael = (Person) session.get(Person.class, 1);
michael.setName("Der Bulla");
session.update(michael);
}
});
Assert.assertEquals(1, michael.getVersion().intValue());
// add a new finger to michael => version counter goes up
doInTransaction(new HibernateMethod() {
@Override
public void run(Session session) {
michael = (Person) session.get(Person.class, 1);
Finger finger = new Finger("Small finger", michael);
michael.addFinger(finger);
session.update(michael);
}
});
Assert.assertEquals(2, michael.getVersion().intValue());
// here's the tricky part: change a finger of michael without any changes to michael itself => version counter goes up
doInTransaction(new HibernateMethod() {
@Override
public void run(Session session) {
michael = (Person) session.get(Person.class, 1);
Assert.assertEquals(michael.getFingers().size(), 4);
Finger anyFinger = michael.getFingers().iterator().next();
anyFinger.setName("Middlefinger");
session.update(anyFinger);
}
});
Assert.assertEquals(3, michael.getVersion().intValue());
}
Assert.assertEquals(3, michael.getVersion().intValue());
失败,因为如果依赖手指发生变化,Hibernate并不关心更新某个人的版本计数器。我能说服Hibernate吗?
答案 0 :(得分:0)
如果我理解你的问题,那么你正在寻找的解决方案可能是
@OptimisticLock(excluded=true)
只需将此注释放入手指集合列表即可。希望我能正确理解你的问题。