使用Hibernate在EJB中通过容器管理事务处理异常

时间:2019-05-13 06:42:57

标签: hibernate ejb weblogic12c

使用容器管理的事务在EJB中捕获休眠异常时遇到问题。

package com.somepackage;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
@TransactionAttribute(TransactionAttributeType.NEVER)
public class MyBusiness {
   @EJB
   Archiver archiver;

   public void doSomething(Request request) {
       try {
             Response response = new Response();
             archiver.archive(request, response);
       } catch (Exception e) {
             e.printStackTrace();
       }
   }
}

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class Archiver {
    @EJB
    private RequestManager requestManager;
    @EJB
    private ResponseManager responseManager;

    public void archive(Request request, Response response) {
        try {
            requestManager.create(request);
            responseManager.create(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class ResponseManager {
    @PersistenceContext(unitName = "datasource")
    private EntityManager entityManager;

    public void create(Response response) {
        try {
            entityManager.persist(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class RequestManager {
    @PersistenceContext(unitName = "datasource")
    private EntityManager entityManager;

    public void create(Request request) {
        try {
            entityManager.persist(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

问题是我无法捕获诸如ConstraintViolationException之类的异常,尽管我可以在Weblogic控制台中看到错误日志,但是我的捕获仅报告事务回滚,仅此而已。

//控制台日志

2019年5月13日上午10:58:09 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions 警告:SQL错误:1400,SQLState:23000 2019年5月13日10:58:09 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions 错误:ORA-01400:无法将NULL插入(“ SCHEMA”。“ REQUEST”。“ REF_EXCEPTION_ID”)

//// log此处结束

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您应该像这样捕获ConstraintViolationException:

try {
    // your logic...
} catch (EJBTransactionRolledbackException e) {
    Throwable t = e.getCause();
    while ((t != null) && !(t instanceof ConstraintViolationException)) {
        t = t.getCause();
    }
    if (t instanceof ConstraintViolationException) {
        // Handle ConstraintViolationException...
    }
}

答案 1 :(得分:0)

我找到了解决方法here

我只需要在Weblogic Env中设置它即可。

set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.transaction.allowOverrideSetRollbackReason=true