【问题标题】:Spring transaction doesn't rollback in classes not instantiated by Spring contextSpring 事务不会在未由 Spring 上下文实例化的类中回滚
【发布时间】:2012-11-02 20:42:34
【问题描述】:

我在 Spring 中处理事务时遇到问题。 我有一个 Web 服务,它简单地迭代一定次数,每次都将一条记录插入到 Oracle 数据库中。我将我的服务的插入方法标记为@Transactional,因为我希望它在任何插入失败时回滚(在 RuntimeException 之后,即在要插入空对象的情况下)。

问题是,如果我通过 java 测试服务,使用通过 Spring 应用程序上下文实例化服务的 main,evertything 工作正常(我得到每条记录回滚)。 相反,如果我用soapUI测试web服务,在本地服务器上部署之后,就像看不到@Transactional注解一样。

我报告我的代码。

这是我的服务:

@Service
public class MyService{

        @Transactional
        public void insert(List<DAO> l) {

              for(DAO item : l) {
              //Insert item into the DB
              //and throw a RunTimeException in case of failure (i.e.,item null)
              }
        }
}

这是我的主要内容:

public class TestMain{

    public static void main(String[] args) {

        ApplicationContext ac = new FileSystemXmlApplicationContext(SPRING_CONTEXT_XML_PATH);

        MyService service = ac.getBean(MyService .class);

        List<DAO> l; //Suppose it is initialized    
        service.insert(l); //Rollback working if RuntimeException is thrown     
}

}

正如我所说,当我使用 Spring 应用程序上下文实例化 Web 服务时,上面的代码可以工作,但是如果我在将 MyService 部署到服务器上之后通过soapUI 调用它(这实际上是服务的目的),@事务未执行。

有人可以向我解释一下这种行为吗?

非常感谢。

【问题讨论】:

  • 你能分享调用这个 Web 服务的 SOAP 代码吗?端点如何获取和调用你的MyService

标签: web-services spring transactions soapui rollback


【解决方案1】:

spring 每次调用insert 方法时都会为你启动一个事务,因为它有@Transactional 注释。当insert 返回时,事务被提交(如果抛出异常则回滚)。

当 spring 创建一个 MyService 类型的 bean 时,它会将 insert 方法包装成这样:

EntityManager em = ...; // get EntityManager here
EntityTransaction tx = null;
try {
    tx = em.getTransaction();
    tx.begin();

    // your insert method is called here.

    tx.commit();
} catch (Exception e) {
    if ( tx != null && tx.isActive() ) {
        tx.rollback();
    }
}

soupUI 不处理 @Transactional 注释。您必须自己启动事务并提交/回滚。

【讨论】:

  • 感谢您的回答。但是部署的服务必须由远程客户端调用(无需从主类在 java 中实例化服务类),并且使用soapUI 我应该测试我的服务的逻辑。谁调用服务会得到与没有事务注释相同的行为(这意味着不会执行回滚)?
猜你喜欢
  • 2017-03-03
  • 2012-03-10
  • 2018-07-15
  • 2018-12-27
  • 2021-04-14
  • 1970-01-01
  • 2019-03-30
相关资源
最近更新 更多