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/wildfly和 tomee/embedded
由于 tomee 似乎无法正确支持“继承”,因此某些测试已停用。
关于jakarta-ee - JAVA EE - EJB/CDI/JPA : Exception Handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45586089/