How to handle JPA unique constraint violations?

后端 未结 8 1781
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 14:05

When a unique constraint is violated, a javax.persistence.RollbackException is thrown. But there could be multiple reasons to throw a RollbackException

相关标签:
8条回答
  • 2020-12-05 14:35

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

    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);
    }
    

    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).

    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.

    0 讨论(0)
  • 2020-12-05 14:37

    You can use the following :

    If you are using spring framework then you can use :

    org.springframework.dao.DataIntegrityViolationException

    If standard JPA following can be used

    org.hibernate.exception.ConstraintViolationException

    At sql level following can be used :

    java.sql.SQLIntegrityConstraintViolationException

    0 讨论(0)
提交回复
热议问题