我有一个外部方法调用内部方法的设置。这个内部方法可能会抛出一个异常,导致它回滚。我不希望这个异常影响外部方法。为此,我在内部方法上使用了@Transactional(propagation=Propagation.REQUIRED_NEW)。
以下是我的代码的简化版本:
public class ServiceAImpl implements ServiceA{
@Autowired
private ServiceB serviceB;
@Transactional(propagation=Propagation.REQUIRED)
public void updateParent(Parent parent) {
update(parent);
serviceB.updateChild(parent);
}
}
public class ServiceBImpl implements ServiceB {
@Transactional(propagation=Propagation.REQUIRED_NEW)
public void updateChild(Parent parent) {
checkIfChildHasErrors(parent.getChild()); //throws RuntimeException if Child has errors
update(parent.getChild());
}
}
public class Parent {
@Version
private Integer version;
private Child child;
//insert getters and setters
}
public class Child {
@Version
private Integer version;
//insert getters and setters
}我仍然是传播的新手,但据我所知,由于外部方法(updateParent)具有Propagation.REQUIRED,内部方法(updateChild)具有Propagation.REQUIRED_NEW,因此它们现在包含在各自独立的事务中。如果内部方法遇到异常,它将回滚,但不会导致外部方法回滚。
当外部方法运行时,它调用内部方法。当内部方法正在运行时,外部方法暂停。一旦内部方法完成,它就会被提交,因为它是一个不同的事务。外部方法取消暂停。并且它也被提交为另一个事务。
我遇到的问题是,提交外部方法的过程触发了Child类的乐观锁定(可能是因为在内部方法结束并提交之后,version字段的值发生了更改)。由于外部方法的Child实例已经过期,因此提交它会触发乐观锁定。
我的问题是:有没有办法防止外部方法触发乐观锁定?
令我惊讶的是,外部方法甚至试图提交对Child类的更改。我假设由于内部方法包含在它自己的事务中,外部方法的事务将不再包含updateChild方法。
我使用的是Spring 3.0.5和Hibernate 3.6.10
发布于 2015-12-08 17:38:42
假设您使用merge进行更新
对于内部事务
Entity entityUpdated = entityManager.merge(entity);对于外部事务
if (entityUpdated != null){
// if inner transaction rolledback entityUpdated will be null. Condition will save u from nullPointerException
outerEntity.setVersion(entityUpdated.getVersion);
}
entityManager.merge(outerEntity);https://stackoverflow.com/questions/34147618
复制相似问题