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

查看:5349
本文介绍了如何处理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天全站免登陆