捕捉 ConstraintViolationException – 不起作用

huangapple go评论70阅读模式
英文:

catch ConstraintViolationException - doesnt work

问题

我无法捕获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("...........");
                // 在这里检查删除日期是否也为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() 来判断是否为 ConstraintViolationException,但代码控制未进入该 catch 块,而是进入了通用的 Exception 块。有人能提供一些建议吗?

英文:

I am unable to catch 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;
}

in this code em.persist(subBoardObj); throws ConstraintViolationException. I tried using getCause() and identify if constraintViolation but the code control doesnt goto that catch block. It goes to generic Exception block. Can someone suggest whats wrong.

答案1

得分: 0

首先,我不建议手动处理事务,而是使用声明式事务管理。如果你使用EJBs,只需将bean注释为@Stateless,或者如果想要更改事务划分策略,在方法上使用@TransactionAttribute注解。如果你真的必须使用手动事务管理,你应该使用UserTransaction接口。这是因为EJB使用JTA规范,而你可能也在持久化单元中将其配置为事务策略。

话虽如此,EntityManager.persistEntityManager.flush会抛出javax.persistence.PersistenceException,该异常包装了org.hibernate.exception.ConstraintViolationException。因此,你需要捕获PersistenceException,然后使用getCause方法获取约束违规信息。

英文:

First of all, I would not recommend doing transaction handling manually but instead use declarative transaction management. If you use EJBs, you just need to annotate the bean as @Stateless or if you want to change the transaction demacration strategy use the @TransactionAttribute annotation on the method. If you really must use manual transaction management you should use the UserTransaction interface. This is because EJB works with the JTA specification which you probably also configured as transaction strategy in your persistence unit.

Having said that, EntityManager.persist and EntityManager.flush throw javax.persistence.PersistenceException that wrap a org.hibernate.exception.ConstraintViolationException. So you need to catch the PersistenceException and then use getCause to get the constraint violation.

huangapple
  • 本文由 发表于 2020年9月25日 01:40:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64051655.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定