我在制作真正的代码之前创建了一个测试代码,只是为了确保它能工作。 这段代码所做的就是在彼此之间启动新的事务并尝试更新两个实体。这很简单。 对我来说,在它离开 transaction3() 方法后,它应该回滚 transaction2Entity 更新,但它不会发生。
persistence.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>
环境异常
@javax.ejb.ApplicationException(rollback=true)
public class EnvioException extends javax.ws.rs.WebApplicationException {
private static final long serialVersionUID = -990622645054458959L;
}
我开始调用 REST API“/transactionService/transaction”的测试代码:
API 休息
@Path("/transactionService")
public class TransactionService {
@EJB
TestTransaction testTransaction;
@Path("/transaction")
@GET
@SemAutenticacao
public void transaction(@Context HttpHeaders headers) throws IOException, SQLException {
testTransaction.transaction1();
}
}
这是主课:
测试交易
@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();
}
}
我该如何解决它?
我不知道为什么,但是当我将 transaction3() 移动到另一个 EJB 类时,它起作用了。我所做的只是这样。