Java 捕获约束ViolationException-不工作

Java 捕获约束ViolationException-不工作,java,hibernate,exception,Java,Hibernate,Exception,我无法捕获ConstraintViolationException public BigDecimal createSubBoard(SubBoard subBoardObj, Users user) { EntityManager em = EMFUtility.getEntityManager(); EntityTransaction et = null; SubBoards subBoard = null; SubBoard subBoards

我无法捕获ConstraintViolationException

public BigDecimal createSubBoard(SubBoard subBoardObj, Users user) {
    EntityManager em = EMFUtility.getEntityManager();     
    EntityTransaction et = null; 
    SubBoards subBoard = null;
    SubBoard subBoards = null;
    Boards board = null;
    BigDecimal subBoardId = new BigDecimal(0);
    try {
        logger.debug(" #### BoardsDao - createSubBoard"+subBoardObj.toString());
        et = em.getTransaction();
        et.begin();

        try{
        subBoardObj.setCreateDate(new Date());
        subBoardObj.setCreatedBy(user.getEdipi());
        em.persist(subBoardObj);
        subBoardId = subBoardObj.getId();
        et.commit();
        } catch(EJBTransactionRolledbackException  ce) {
            System.out.println("!!!");
            Throwable t = ce.getCause();
                while ((t != null) && !(t instanceof ConstraintViolationException)) {
                    t = t.getCause();
                }
                if (t instanceof ConstraintViolationException) {
                    System.out.println("...........");
                    // Check here if the delete date is also null
                }
        }   

        ///TODO..///    
        
    } catch (Exception e) {
        et.rollback();
        e.printStackTrace();
        System.out.println("!!!! "+e.getCause() );
        logger.debug(" #### BoardsDao - createSubBoard :Exception is " + e.getMessage());
        throw new PersistenceException("Error persisting entity in createSubBoard "+ e.getMessage());
    } finally {
        em.close();
    } 
    return subBoardId;
}

在此代码中,em.persist(subBoardObj);抛出ConstraintViolationException。我尝试使用getCause()并确定constraintViolation是否存在,但代码控件没有转到该catch块。它转到通用异常块。有人能提出什么问题吗。

首先,我不建议手动执行事务处理,而是使用声明式事务管理。如果您使用EJB,您只需要将bean注释为
@Stateless
,或者如果您想要更改事务数据描述策略,请在方法上使用
@TransactionAttribute
注释。如果确实必须使用手动事务管理,则应使用
UserTransaction
界面。这是因为EJB使用JTA规范,您可能还将其配置为持久化单元中的事务策略

话虽如此,
EntityManager.persist
EntityManager.flush
throw
javax.persistence.PersistenceException
包装了
org.hibernate.exception.ConstraintViolationException
。因此,您需要捕获PersistenceException,然后使用
getCause
获取约束冲突