gpt4 book ai didi

java - 事务不回滚

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:32:32 26 4
gpt4 key购买 nike

我调用了两个方法,第一个更新表,下一个在另一个表中插入记录。当第二个事务失败时,EJB 没有执行第一个事务的回滚。

这是我的支持 bean:

@ManagedBean
@ViewScoped
public class TransactionTestBean implements Serializable {

@EJB
private TransactionTestService service;

public String loadView() {
return "/test/transactionTest";
}

public void test() {
try {
service.updateTest();
} catch (Exception e) {
}
}
}

EJB 接口(interface):

@Local
public interface TransactionTestService {

void updateTest() throws CustomException;
}

EJB 类:

@Stateless
@TransactionManagement
public class TransactionTestServiceImpl implements TransactionTestService {

@Resource(mappedName = "java:jboss/datasources/xxxxxDS", shareable = true)
public DataSource dataSource;

private TransactionTestDAO dao;

@PostConstruct
public void init() {
dao = new TransactionTestDAOImpl();
}

@PreDestroy
public void destroy() {
dao = null;
}

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateTest() throws CustomException {

try (Connection connection = dataSource.getConnection()) {
dao.updateRecord(connection);
// dao.saveRecord(connection);
} catch (SQLException exception) {
throw new CustomException(exception, exception.getMessage());
}
}
}

还有我的自定义异常:

@ApplicationException(rollback = true)
public class CustomException extends Exception {

public CustomException(Throwable cause, String message) {
super(message, cause);
}
}

已编辑:

添加了 DAO 类:

public class TransactionTestDAOImpl implements TransactionTestDAO {

@Override
public void updateRecord(Connection connection) throws CustomException {

PreparedStatement preparedStatement = null;

try {
preparedStatement = connection.prepareStatement("UPDATE table_x SET field_x = ? WHERE field_y = 1");
preparedStatement.setInt(1, 1);
preparedStatement.executeUpdate();
} catch (Exception exception) {
throw new CustomException(exception, exception.getMessage());
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException sqlException) {
}
}
}
}
}

和 DAO 接口(interface):

public interface TransactionTestDAO {

void updateRecord(Connection connection) throws CustomException;
}

最佳答案

这个案例中的关键问题是某些 JBoss 版本中数据源的错误默认设置。原始代码很好,并且在其他应用程序服务器(WebSphere App Server 和轻量级 WebSphere Liberty)中工作正常。

在 JBoss 中创建的数据源不是 JTA - 在管理控制台中 Use JTA设置未选中,在 xml 中相关设置为 <datasource jta="false" ... .将此设置更改为 true解决了问题。 (JohnB,你写道定义 xa-datasource 修复了这个问题,但由于我没有看到你的原始 xml 和数据源定义,我相信在更改数据源期间你也更改了这个有缺陷的 jta="false"设置)。正如 Grzesiek 测试的那样,它也适用于非 xa 数据源。

这是一个非常糟糕的默认值,因为它会导致事务不受容器管理,并且会导致 EJB 组件中的连接出现错误的事务行为

非常感谢Grzesiek D.谁帮我诊断了这个问题。

关于java - 事务不回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26151636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com