【问题标题】:org.hibernate.StaleStateException: Batch update returned unexpected row countorg.hibernate.StaleStateException:批量更新返回意外的行数
【发布时间】:2016-09-09 07:26:29
【问题描述】:

我有一个架构,我有 3 个表。假设 A、B、C。 A是child的父表,B,C是子表。

当我调用 hibernateSession.saveOrUpdate 它是更新所有三个表。

但是在子表中我没有父表的数据,但在父表中我有数据。所以它给出了异常

 org.hibernate.StaleStateException: Batch update returned
unexpected row count from update [0]; actual row count: 0; expected: 1.

所以我想知道休眠中是否有任何方法,以便如果子表没有数据,则在更新父表数据时插入其他更新。

编辑 1:

这样打印的查询

Update A set name =? where aid = ?
Update B set adder =? where bid = ?
Update C set city =? where cid = ?

但我在 B 和 C 表中没有记录。

编辑:2

所以如果表B和C都没有数据则插入数据。

这是我的代码。

A a = session.get(aid);
B b = a.getb();
C c = a.getc();
// Save B if not exists in database
if (b != null) {
    if (b.bid() != null) {

        if (session.get(b.bid()) == null) {
            System.out.println("--record is there in db---");
            session.save(b);
        }
    }
}

// Save C if not exists in database
if (c != null) {
    if (c.cid() != null) {

        if (session.get(c.cid()) == null) {
            System.out
                    .println("--record is there in db in update---");
                session.save(c);
            }
        }
    }
}

但我遇到了这个异常。

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

【问题讨论】:

    标签: java hibernate batch-processing


    【解决方案1】:

    您可以在休眠配置中设置 show_sql = true。 然后你可以看到抛出异常的更新语句。 不看你的数据类型就说些什么是不够的, 表和关系。

    【讨论】:

      【解决方案2】:

      我建议在您的 Hibernate.cfg.xml 配置中打开休眠语句日志记录,以了解发生了什么,因为您没有发布表结构和查询。

      启用 Hibernate 语句日志记录:

      <property name="show_sql">true</property>
      <property name="format_sql">true</property>
      <property name="use_sql_comments">true</property>
      

      那么请使用打印的查询更新您的问题。

      编辑 1:

      更新具有表中不存在的 id 的对象时会引发此异常。该错误意味着它无法找到具有您给定 ID 的记录。

      为避免这种情况:

      你应该读取相同id的记录:

    • 如果它找到一条记录,然后调用update

    • 否则抛出它并显示如下错误

      找不到异常记录。

      编辑 2

      关于这个错误:

      休眠错误:org.hibernate.NonUniqueObjectException:具有相同标识符值的不同对象已与会话关联

      您应该告诉休眠会话将您修改的对象与会话中的对象合并

      session.merge(object)
      
    • 【讨论】:

      • 为此我需要先插入然后更新。没有显示任何错误
      • 使用合并获取异常后。[AssertionFailure] 发生断言失败(这可能表明 Hibernate 中存在错误,但更可能是由于会话使用不安全) org.hibernate.AssertionFailure: null 标识符
      猜你喜欢
      • 2014-03-04
      • 1970-01-01
      • 2011-04-20
      • 2019-11-05
      • 1970-01-01
      • 2023-03-09
      • 2017-12-09
      相关资源
      最近更新 更多