jakarta-ee - JAVA EE - EJB/CDI/JPA : Exception Handling

标签 jakarta-ee exception ejb

EJB container considers exceptions in two ways −

  • Application Exception − If business rule is violated or exception occurs while executing the business logic.

  • System Exception − Any exception, which is not caused by business logic or business code. RuntimeException, RemoteException are SystemException. For example, error during EJB lookup. RuntimeException, RemoteException are SystemException.

-> 这是否意味着我需要对我的业务逻辑使用检查异常?像这样吗?

    private void checkConstraints(Object object) throws ValidationException{
    Set<ConstraintViolation<Object>> constraintsAdress = this.getValidator().validate(object);
    if(!constraintsAdress.isEmpty()){
        String fullErrorConstraint = "";
        for (ConstraintViolation<Object> constraint : constraintsAdress) {
            fullErrorConstraint = fullErrorConstraint + constraint.getMessage() + "\n";
        }
        throw new ValidationException(fullErrorConstraint);
    }
}

@Override
public long addCafe(Cafe cafe) throws ValidationException, DBException{
    this.checkConstraints(cafe.getAddress());
    for(FootballMatch footballMatch: cafe.getNextMatchesToWatch()){
        this.checkConstraints(footballMatch);
    }
    this.checkConstraints(cafe);
    this.getManager().persist(cafe);
    return cafe.getCafeID();
}

但是...

An application exception does not automatically result in marking the transaction for rollback unless the ApplicationException annotation is applied to the exception class and is specified with the rollback element value true…

我已经不太明白了... 使用以下方法是个好主意吗:

  • @ApplicationException(rollback = true) ?
  • 那么您也可以使用这个来发出未经检查的异常吗?

提前谢谢 干杯 汤姆

最佳答案

  • ImO @ApplicationException(rollback = true) 是一个好主意,因为这样容器的行为就被定义了。一旦出现这样的异常,回滚是肯定的。
  • 您还可以将未经检查的异常声明为 ApplicationException。

如果您有兴趣,我使用以下测试比较了 tomee 和 wildfly 的行为: Baseclass-Bean for test

实际的测试类是:

arquillian/wildflytomee/embedded

由于 tomee 似乎无法正确支持“继承”,因此某些测试已停用。

关于jakarta-ee - JAVA EE - EJB/CDI/JPA : Exception Handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45586089/

相关文章:

java - 如何将遗留 Java/J2EE 网站移植到现代脚本语言(PHP、Python/Django 等)?

java - 什么时候应该使用Java Extension Class Loader?

java - 后续访问时抛出 Derby LockAcquisitionException

java - @RunAs 用于@WebService EJB

java - 从远程 EJB 调用返回大文件

java - 来自 xml 文件的 jdbc 连接

Java EE通过代理获取IP

java - 我如何将异常从 servlet 过滤器传递到 Spring 组件

java - 从 onClickListener 内部处理深度异常

java.lang.IllegalArgumentException : Sniffers with type [ejb] and type [appclient] should not claim the archive at the same time