我无法捕获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块。转到通用异常块。有人可以提出什么问题吗?
答案 0 :(得分:0)
首先,我不建议手动进行事务处理,而应使用声明式事务管理。如果使用EJB,则只需将bean注释为@Stateless
,或者如果您想更改事务破坏策略,请在方法上使用@TransactionAttribute
注释。如果确实必须使用手动事务管理,则应该使用UserTransaction
界面。这是因为EJB与JTA规范一起使用,您可能还将其配置为持久性单元中的事务策略。
话虽如此,EntityManager.persist
和EntityManager.flush
抛出javax.persistence.PersistenceException
,它们包裹了org.hibernate.exception.ConstraintViolationException
。因此,您需要捕获PersistenceException,然后使用getCause
来获取约束违规。