When a unique constraint is violated, a javax.persistence.RollbackException
is thrown. But there could be multiple reasons to throw a RollbackException
Use e.getCause()
to examine what caused the rollback.
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
}
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.
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);
}
i think printing the stack trace will help you to know this. e.printStackTrace();
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'