EJB Hibernate 嵌套事务不回滚,尽管我抛出了一个用 @ApplicationException(rollback=true) 注释的异常

EJB Hibernate Nested Transaction doesn't Roll Back despite I throw an Exception annotated with @ApplicationException(rollback=true)

提问人:Renato 提问时间:10/20/2023 更新时间:10/21/2023 访问量:14

问:

在制作真实代码之前,我创建了一个测试代码,以确保它能够正常工作。 此代码所做的只是在彼此之间启动新事务,并尝试更新两个实体。这很简单。 对我来说,在它离开 transaction3() 方法后,它应该回滚 transaction2Entity 更新,但它没有发生。

持久性 .xml

<persistence version="2.0"
   xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
        http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="sac">      
      <jta-data-source>java:jboss/datasources/sacDS</jta-data-source>
      <class>org.hibernate.envers.DefaultRevisionEntity</class>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
         <property name="hibernate.show_sql" value="false"/>
         <property name="hibernate.format_sql" value="true"/>         
         <property name="hibernate.hbm2ddl.auto" value="validate"/>         
      </properties>     
   </persistence-unit>
</persistence>

EnvioException(恩维奥异常)

@javax.ejb.ApplicationException(rollback=true)
public class EnvioException extends javax.ws.rs.WebApplicationException {

    private static final long serialVersionUID = -990622645054458959L;

}

我调用 REST API “/transactionService/transaction” 开始我的测试代码:

API REST协议

@Path("/transactionService")
public class TransactionService {
    @EJB
    TestTransaction testTransaction;

    @Path("/transaction")
    @GET
    @SemAutenticacao
    public void transaction(@Context HttpHeaders headers) throws IOException, SQLException {
        testTransaction.transaction1();
    }
}

这是主类:

TestTransaction 测试事务

@Stateless
public class TestTransaction {

    @Inject
    protected EntityManager em;

    public void transaction1() throws IOException, SQLException {
        transaction2();
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void transaction2() throws IOException, SQLException {
        TransactionEntity transactionEntity = em.find(TransactionEntity.class, 1L);
        transactionEntity.setNome("Joe");
        
        try {
            transaction3();
        } catch(EnvioException e) {
            System.out.println("Exception Handled here!");
        }
    }
        
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void transaction3() throws EnvioException {
        Transaction2Entity transaction2Entity = em.find(Transaction2Entity.class, 2L);
        transaction2Entity.setNome("Joe");
        
        throw new EnvioException();
    }
}

我该如何解决?

Hibernate EJB 回滚 JTA 嵌套事务

评论


答:

0赞 Renato 10/21/2023 #1

我不知道为什么,但是当我将 transaction3() 移动到另一个 EJB 类时,它起作用了。我所做的就是这样。