我有一个 DAO,我需要在其中捕获唯一约束异常。为此,唯一可行的解决方案是在持久化之后刷新我的 EntityManager。只有这样我才进入一个捕获块,我必须过滤掉异常。而且,我的 DAO 方法需要包装在事务 (REQUIRES_NEW) 中,否则我有 RollBackException。
难道我做错了什么?
try {
em.persist(myObject);
em.flush();
} catch (PersistenceException ex) {
if (ex.getCause() != null) {
String cause = ex.getCause().toString();
if (cause != null) {
if (cause.contains("org.hibernate.exception.ConstraintViolationException")) {
logger
.error("org.hibernate.exception.ConstraintViolationException: possible unique constraint failure on name");
throw ex;
}
}
}
}