休眠删除错误:批量更新返回意外的行计数

2022-09-02 00:27:01

我在下面写了这个方法,假设从数据库中删除成员记录。但是当我在我的servlet中使用它时,它会返回一个错误。

会员道班

public static void deleteMember(Member member) {
    Session hibernateSession = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = hibernateSession.beginTransaction();
    hibernateSession.delete(member);
    tx.commit();
}

控制器部件

if(delete != null) {
    HttpSession httpSession = request.getSession();
    Member member = (Member) httpSession.getAttribute("member");

    MemberDao.deleteMember(member);

    nextPage = "ledenlijst.jsp";
}

HTTP 状态 500

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

有时,当我尝试多次执行页面时,它甚至会抛出此错误。

org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update

有谁知道究竟是什么导致了这些错误?


答案 1

该错误可能是由多种原因引起的。我不是在为它而功劳,在这里找到了它。

  1. 在提交对象之前刷新数据可能会导致清除所有待定对象以进行持久化。
  2. 如果对象具有自动生成的主键,并且您强制分配了一个键
  3. 如果要在将对象提交到数据库之前清理对象。
  4. 零或不正确的 ID:如果将 ID 设置为零或其他值,Hibernate 将尝试更新而不是插入。
  5. 对象已过时:休眠缓存会话中的对象。如果对象被修改,而Hibernate不知道它,它将引发此异常 - 请注意StaleStateException

另请查看beny23的这个答案,它提供了一些进一步的提示来找到问题。

  • 在休眠配置中,将hibernate.show_sql设置为 true。这应该会显示已执行并导致问题的 SQL。
  • 将 Spring 和 Hibernate 的日志级别设置为 DEBUG,同样,这将使您更好地了解导致问题的行。
  • 创建一个单元测试,该测试无需在Spring中配置事务管理器即可复制问题。这应该可以让您更好地了解违规的代码行。

答案 2

当 Hibernate 注意到他要刷新到数据库的实体与事务开始时的实体不完全相同时,将引发异常。org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

我在这里详细描述了发生在我身上的两种不同的用例。