我调用两种方法,第一种更新表,下一种方法在另一个表中插入记录.当第二个事务失败时,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接口:
@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接口:
public interface TransactionTestDAO {
void updateRecord(Connection connection) throws CustomException;
}