【问题标题】:ConstraintViolationException VS DataIntegrityViolationExceptionConstraintViolationException VS DataIntegrityViolationException
【发布时间】:2009-08-07 20:20:14
【问题描述】:

我正在编写一个Spring应用程序,似乎当我遇到数据库错误时,有时会抛出Hibernate的ConstraintViolationException,有时会抛出Spring的DataIntegrityViolationException。是否有原因可能会抛出一个而不是另一个?它们的意思不同吗?

【问题讨论】:

    标签: hibernate spring


    【解决方案1】:

    如果您通过 HibernateTemplate 执行 Hibernate 调用,那么 Spring 会将任何 Hibernate 异常(例如 ConstraintViolationException)转换为 Spring 异常层次结构(例如 DataIntegrityViolationException)。如果您不使用HibernateTemplate,那么本机Hibernate 异常将通过。两者都是RuntimeExceptions,所以不需要显式的异常处理,所以你会看到哪一个并不总是很明显。

    【讨论】:

    • 我没有使用HibernateTemplate,但是只有当主键被违反时,我才会得到 Spring 的包装器异常。其他唯一键违规会导致 Hibernate 异常。代码是相同的——只有被违反的密钥类型很重要。
    • 你在你的 DAO 上使用了@Repository 注解吗?
    猜你喜欢
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多