【问题标题】:PostgreSQL exception when deleting object in one-to-many relationship using Hibernate使用 Hibernate 删除一对多关系中的对象时 PostgreSQL 异常
【发布时间】:2012-11-23 21:46:51
【问题描述】:

我有非常简单的架构 - 一对多关系中的两个表:

<hibernate-mapping package="my.app">
    <class name="CorrelationKey" table="CORRELATION_KEYS">
        <id name="id" column="CORRELATION_ID">
            <generator class="native"/>
        </id>
        <set name="correlationKeyParts" cascade="all-delete-orphan" lazy="false">
            <key column="CORRELATION_ID"/>
            <one-to-many class="CorrelationKeyPart"/>
        </set>
        ...
    </class>
</hibernate-mapping>

CorrelationKey 类型的对象的保存和更新工作正常,并且更改传播到集合。但是当我尝试删除 CorrelationKey 对象时,我收到以下错误:

108090 [main] ERROR org.hibernate.util.JDBCExceptionReporter  - ERROR: update or 
delete on table "correlation_keys" violates foreign key constraint "fk23630e23e9b29c52"
on table "correlation_key_parts"
 Detail: Key (correlation_id)=(162) is still referenced from table "correlation _key_parts".

我在 Windows 机器上使用 PostgreSQL 9.1。

非常感谢。

【问题讨论】:

  • @JBNizet 我在尝试清空表 session.createQuery("delete from CorrelationKey").executeUpdate(); 时看到错误。感谢您查看此内容。

标签: hibernate postgresql hibernate-onetomany


【解决方案1】:

当您执行这样的 DML 查询时,会完全绕过会话缓存、级联和版本检查。查询直接转换为 SQL 查询并按原样执行。因此,您有责任首先删除(或修改)相关实体。如果要应用级联,则需要使用 Hibernate API:

List<CorrelationKey> allKeys = session.createQuery("select k from CorrelationKey k").list();
for (CorrelationKey key : allKeys) {
    session.delete(key);
}

【讨论】:

  • 是的。你搞定了。非常感谢您的帮助。我很感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多