简体   繁体   English

区分休眠中不同的约束违规

[英]Differentiate between different constraint violations in hibernate

I have a database table which has both Foreign key and Unique key constraints. 我有一个同时具有外键和唯一键约束的数据库表。 To make changes in the database table, i am using java application which uses hibernate. 为了更改数据库表,我正在使用使用休眠的Java应用程序。 To be more precise i am doing Session.save() to make changes in database table. 更准确地说,我正在执行Session.save()在数据库表中进行更改。 My code looks like this. 我的代码如下所示。

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

In case of any type constraint violation hibernate throws the same exception named ConstraintViolationException . 如果发生任何类型的约束冲突,hibernate都会抛出一个名为ConstraintViolationException异常。

My question is what should i do to identify that what constraint has caused the exception. 我的问题是我应该怎么做才能确定是什么约束导致了异常。 I tried doing 我试着做

exception.getConstraintName()

But unfortunately i am getting null as output. 但是不幸的是我的输出为null

I want to differentiate between the two cases because i want to translate the hibernate exception to my own exception before sending it to client. 我想区分这两种情况,因为我想先将休眠异常转换为我自己的异常,然后再将其发送给客户端。

I would say let the database detect the violations of the constraint..... 我想说的是让数据库检测到违反约束的情况.....

Or 要么

You can have something like the below class which might help in your case to catch the constraint violation exceptions... 您可以使用类似下面的类,这可能有助于您捕获约束违例异常。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM