如何处理 JPA 唯一约束违规? [英] How to handle JPA unique constraint violations?

查看:44
本文介绍了如何处理 JPA 唯一约束违规?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当违反唯一约束时,会抛出 javax.persistence.RollbackException.但是引发 RollbackException 的原因可能有多种.我如何才能发现违反了唯一约束?

When a unique constraint is violated, a javax.persistence.RollbackException is thrown. But there could be multiple reasons to throw a RollbackException. How can I find out that a unique constraint was violated?

try {
    repository.save(article);
}
catch(javax.persistence.RollbackException e) {
    // how to find out the reason for the rollback exception?
}

推荐答案

如何发现违反了唯一约束?

How can I find out that a unique constraint was violated?

异常是链式的,您必须递归调用 getCause() 以获取提供者特定的异常(并且可能转到 SQLException)以将其转换为您的应用程序可以很好地为您的用户处理.以下将打印异常链:

Exception are chained, you have to call getCause() recursively to get the provider specific exception (and maybe go down to the SQLException) to translate it into something your application can handle nicely for your user. The following will print the chain of exception:

for (t = e.getCause(); t != null; t = t.getCause()) {
    logger.debug("Exception:" + t);
}

对于异常处理和翻译",您可以执行类似于 Spring 的操作(请参阅各种 JpaDialect 类,例如 HibernateJpaDialect 来了解一下.

For the exception handling and the "translation", you could do something like what Spring does (see the various JpaDialect classes, e.g. HibernateJpaDialect to get an idea).

这一切都不好,此代码不可移植,并且查找导致违规的属性并不容易.这在某种程度上证实了没有 优雅和便携的方式来处理约束违规JPA.

All this is not nice, this code won't be portable and finding what attribute(s) caused the violation won't be easy. This somehow confirms that there is no elegant and portable way to handle constraint violations in JPA.

这篇关于如何处理 JPA 唯一约束违规?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆