java - 区分 hibernate 中不同的约束违规

标签 java mysql database hibernate spring-jdbc

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

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

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

我的问题是我应该做什么来确定是什么约束导致了异常。我尝试做

exception.getConstraintName()

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

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

最佳答案

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

或者

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

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

关于java - 区分 hibernate 中不同的约束违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22586576/

相关文章:

php - 注册页面: Storing password using PHPASS

java - 在 Hibernate 中使用 saveOrUpdate() 创建新记录而不是更新现有记录

java - 无法为 SqlServer 连接器设置 debezium 嵌入式引擎

java - 在 Java 中的多态数组对象上运行方法时出现问题

php - Insert_batch错误代码igniter 3.1.4

java - 如何在java中动态连接mysql数据库并显示所选数据库的表、属性?

android - 如果我在另一台设备上安装该应用程序,是否仍然可以使用预制 ID 登录?

java - 如何在java中添加弹出窗口到jtextFiled View

java - Apache CXF : how to return failure response from an interceptor

mysql - 优化查询以计算一张表的两个不同列和不同行的总计