java - Hibernate:删除前检查外键约束违规?

标签 java spring hibernate foreign-keys constraints

我目前正在使用的系统有一个策略,其中没有关系的对象可以自由删除,而那些有关系的对象必须逻辑删除。这是为了防止历史信息被删除。

所以基本上,我试图做的是确定一个对象的键当前是否存在于另一个表中。如果不是,我会简单地调用 delete(),否则我会设置一个指示逻辑删除的属性,然后调用 update()。

我正在使用 Spring 事务管理,因此我试图尽可能不干扰 session 本身。我最初的方法一开始似乎奏效,但您会发现它有一个重大缺陷:

@Transactional
public void deleteObject(SomeEntity object)
{       
    //try to delete
    this.someEntityDAO.delete(object);

    try //force foreign key constraint check
    {
        this.someEntityDAO.flush();
    }
    catch (ConstraintViolationException e)
    {
        //reload object
        object= this.someEntityDAO.loadById(object.getId());

        //save as inactive instead of deleting
        object.setActive(false);
        this.someEntityDAO.update(object);
    }
}

因为 Hibernate 异常是致命的,所以这是完全不可靠的(即使它有效)。我想知道是否有一种方法可以执行某种“窥视”操作,我可以在其中测试删除是否会因约束而失败,而无需实际执行该操作(从而使 session 无效)。我唯一能想到的就是手动检查每个相关表以查看id是否存在,但是这在具有许多关系的表中会非常繁琐且容易出错。如果可能,我想利用数据库中已有的约束。

最佳答案

专门针对:

So basically, what I was trying to do was determine whether an object's key is currently present in another table. If it isn't I would simply call delete(), otherwise I would set a property that indicates a logical delete, and call update().

和:

I was wondering if there is a way to do a sort of "peek" operation in which I could test if the delete will fail due to a constraint, without actually performing the operation (and thus invalidating the session).

我只是偶尔使用 Hibernate,但一般的回答是:这就是 SQL 的用途。这一切都在你的 where 子句中!

为清楚起见:您使用足够的 where 子句进行删除,它会在事务本身中进行检查;删除会删除满足给定约束的任何内容。

更新:

当你写的时候:

"So basically, what I was trying to do was determine whether an object's key is currently present in another table. If it isn't I would simply call delete(), otherwise I would set a property that indicates a logical delete, and call update()."

问题是当您应该让(指示)数据库引擎在您的 SQL 中为您执行此操作时,您正在尝试执行此操作。调查“不存在”条款的使用...

关于java - Hibernate:删除前检查外键约束违规?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474629/

相关文章:

java - 此脚本中的 int 和 Integer 有什么区别?

java - Spring Boot应用程序中的资源访问

java - 在运行时重新调度 Quartz

java - hibernate中属性名、逻辑名和物理名的区别

java - hibernate 标准顺序不起作用

java - JApplets : Loading Images

java - 安装 Node.js 应用程序时版本不匹配

java - 为通过参数返回的函数创建类型映射

java - Spring : Schedule a task which takes a parameter

java - 你如何学习一个框架?