How to handle JPA unique constraint violations?

后端 未结 8 1780
爱一瞬间的悲伤
爱一瞬间的悲伤 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:13

    Use e.getCause() to examine what caused the rollback.

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

    compiler returns the exception SQLIntegrityConstraintViolationException, while trying to violate unique constraint.

    Use the following catch block concept, to handle proper exceptions.

    catch(SQLIntegrityConstraintViolationException e) 
    {
      // Error message for integrity constraint violation
    }
    catch(Exception e)
    {
     // Other error messages
    }
    
    0 讨论(0)
  • 2020-12-05 14:19

    You can do like this :

    StringWriter writer=new StringWriter(); //remains the message from stack trace.
    e.printStackTrace(new PrintWriter(writer));
    String message=writer.toString(); // gets the message of full stack trace.
    

    And then view the information of exception.

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

    This might very late for you but here's how I solved it for PostGres.

    catch (DataIntegrityViolationException e) {
    
                for (Throwable t = e.getCause(); t != null; t = t.getCause()) {
    
                    if (PSQLException.class.equals(t.getClass())) {
                        PSQLException postgresException = (PSQLException) t;
    
                        // In Postgres SQLState 23505=unique_violation
                        if ("23505".equals(postgresException.getSQLState())) {
                            throw new CustomDataAlreadyExistsException("YourErrorCode", e);
                        }
                    }
                }
                throw new SomeOtherException("YourErrorCode2", e);
    
            }
    
    0 讨论(0)
  • 2020-12-05 14:28

    i think printing the stack trace will help you to know this. e.printStackTrace();

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

    You have to catch javax.persistence.PersistenceException. Thrown exception is org.hibernate.exception.ConstraintViolationException.

    Exception Message : org.hibernate.exception.ConstraintViolationException: Duplicate entry '893073116V-1234567' for key 'nic_account_no'

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