微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在org.springframework.dao.DataIntegrityViolationException中获取约束名称?

在我的应用程序中,当提出违规密钥时,我想获得约束名称,但我找不到任何获取此信息的方法. “getMessage()”返回的消息非常概括,我需要有关错误的更多信息,以便向最终用户发出可自定义错误消息.

堆栈跟踪:

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,29) already exists.

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]

谢谢.

亚瑟

最佳答案
包装异常通常可以将原始异常嵌套在其中.对于Hibernate,您的ConstraintViolationException是JDBCException,它有一个名为getSQLException方法,它返回实际的异常.因此,在Spring DataIntegrityViolationException上调用getCause(为了获得Hibernate异常),在其上调用getsqlException,最后在sqlException上调用getMessage().该消息应与您在Hibernate JDBCExceptionReporter中看到的消息相同,如果您只需要解析字符串的约束名称.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐