Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the constraint name in a org.springframework.dao.DataIntegrityViolationException?

In my application when a violation key is raised, I would like to get the constraint name, but I'm not finding any method to get this information. The message returned by "getMessage()" is very summarized and I need more information about the error to make a customizable error message to the end user.

The stack trace:

84732 [http-8080-1] WARN  org.hibernate.util.JDBCExceptionReporter  - SQL Error: 0, SQLState: 23505
84732 [http-8080-1] ERROR org.hibernate.util.JDBCExceptionReporter  - ERROR: duplicate key value violates unique constraint "ix_tb_oferta_vaga"
  Detalhe: Key (cd_pj, cd_curso)=(680, 29) already exists.
187405 [http-8080-1] WARN  org.hibernate.util.JDBCExceptionReporter  - SQL Error: 0, SQLState: 23505
187405 [http-8080-1] ERROR org.hibernate.util.JDBCExceptionReporter  - ERROR: duplicate key value violates unique constraint "ix_tb_oferta_vaga"
  Detalhe: Key (cd_pj, cd_curso)=(680, 29) already exists.

The getMessage():

could not insert: [br.gov.ce.seduc.estagio.model.bean.OfertaVaga]; nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [br.gov.ce.seduc.estagio.model.bean.OfertaVaga]

Thanks.

Arthur

like image 835
Arthur Accioly Avatar asked Aug 18 '11 16:08

Arthur Accioly


2 Answers

Insert a catch statement like this:

catch (DataIntegrityViolationException e) {
        String message = e.getMostSpecificCause().getMessage();
}
like image 191
Guilherme Berghauser Avatar answered Sep 29 '22 21:09

Guilherme Berghauser


Wrapping exceptions usually have a way to nest the original exception within them. For Hibernate, your ConstraintViolationException is a JDBCException, it has a method called getSQLException that returns the actual exception. So call getCause on the Spring DataIntegrityViolationException (in order to get the Hibernate exception), call getSQLException on that, and finally call getMessage() on the SQLException. The message should be the same as what you see logged by the Hibernate JDBCExceptionReporter, if you want only the constraint name you will have to parse the string.

like image 26
Nathan Hughes Avatar answered Sep 29 '22 20:09

Nathan Hughes