java - 捕获 ConstraintViolationException - 不起作用
问题描述
我无法捕捉 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 块。它转到通用异常块。有人可以建议什么是错的。
解决方案
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.