首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Transaction Propagation和乐观锁定问题

Spring Transaction Propagation和乐观锁定问题
EN

Stack Overflow用户
提问于 2015-12-08 11:45:27
回答 1查看 1.8K关注 0票数 4

我有一个外部方法调用内部方法的设置。这个内部方法可能会抛出一个异常,导致它回滚。我不希望这个异常影响外部方法。为此,我在内部方法上使用了@Transactional(propagation=Propagation.REQUIRED_NEW)。

以下是我的代码的简化版本:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

发布于 2015-12-08 17:38:42

假设您使用merge进行更新

对于内部事务

代码语言:javascript
复制
Entity entityUpdated = entityManager.merge(entity);

对于外部事务

代码语言:javascript
复制
if (entityUpdated != null){
    // if inner transaction rolledback entityUpdated will be null. Condition will save u from nullPointerException
    outerEntity.setVersion(entityUpdated.getVersion);
}

entityManager.merge(outerEntity);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34147618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档