我有一个 DAO,我需要在其中捕获唯一的约束异常。为此,唯一可行的解决方案是在持久化之后刷新我的 EntityManager。只有这样我才能进入一个catch块,我必须过滤掉异常。而且,我的 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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)