How to get restriction name in org.springframework.dao.DataIntegrityViolationException?

In my application, when the violation key is raised, I would like to get the name of the restriction, but I find no way to get this information. The message returned by "getMessage ()" is very summarized, and I need to get additional error information in order to make a custom error message to the end user.

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. 

GetMessage () function:

 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

+4
source share
2 answers

Cover exceptions usually have a way to put the original exception in them. For Hibernate, your ConstraintViolationException is a JDBCException, it has a getSQLException method that returns the actual exception. So call getCause on Spring DataIntegrityViolationException (to get the Hibernate exception), call getSQLException and finally call getMessage () on SQLException. The message should match what you see in the Hibernate JDBCExceptionReporter log if you only need the name of the constraint that you will need to parse.

+2
source

Insert the catch statement as follows:

 catch (DataIntegrityViolationException e) { String message = e.getMostSpecificCause().getMessage(); } 
+3
source

All Articles