【问题标题】:Differentiate between different constraint violations in hibernate区分hibernate中不同的约束违规
【发布时间】:2014-03-23 03:07:15
【问题描述】:

我有一个同时具有外键和唯一键约束的数据库表。为了在数据库表中进行更改,我正在使用使用休眠的 java 应用程序。更准确地说,我正在做Session.save() 对数据库表进行更改。我的代码如下所示。

try{
    transaction.begin();
    ------logic-------
    session.save();
    transaction.commit();
}catch(ConstarintViolationException exception){
    ---here is problem------
}

如果发生任何类型约束冲突,hibernate 会抛出名为ConstraintViolationException 的相同异常。

我的问题是我应该怎么做才能确定是什么约束导致了异常。我试过做

exception.getConstraintName()

但不幸的是,我得到了null 作为输出。

我想区分这两种情况,因为我想在将休眠异常发送给客户端之前将其转换为我自己的异常。

【问题讨论】:

    标签: java mysql database hibernate spring-jdbc


    【解决方案1】:

    我想说让数据库检测违反约束的情况.....

    或者

    您可以使用类似以下类的内容,这可能有助于您捕获违反约束的异常...

    public class DataIntegrityViolationExceptionsAdvice {
        public void afterThrowing(DataIntegrityViolationException ex) throws DataIntegrityViolationException {
            // extract the affected database constraint name:
            String constraintName = null;
            if ((ex.getCause() != null) && (ex.getCause() instanceof ConstraintViolationException)) {
                constraintName = ((ConstraintViolationException) ex.getCause()).getConstraintName();
            }
            // create a detailed message from the constraint name if possible
            String message = ConstraintMsgKeyMappingResolver.map(constraintName);
            if (message != null) {
                throw new DetailedConstraintViolationException(message, ex);
            }
            throw ex;
        }
    }
    

    【讨论】:

    • 不幸的是,我得到“null”作为 getConstraintName() 方法的输出 :-( :-(
    猜你喜欢
    • 2013-11-27
    • 2012-09-11
    • 2020-03-28
    • 2015-09-02
    • 1970-01-01
    • 2011-04-19
    • 2019-04-08
    • 2022-01-23
    • 2015-11-03
    相关资源
    最近更新 更多