MySQL org.hibernate.AssertionFailure: null id in entry (don’t flush the Session after an exception occurs)错误


<!–

–>

MySQL org.hibernate.AssertionFailure: null id in entry (don’t flush the Session after an exception occurs)错误

阅读更多:

问题描述

在使用Hibernate框架连接MySQL数据库时,可能会遇到以下异常:

org.hibernate.AssertionFailure: null id in entry (don’t flush the Session after an exception occurs)

(adsbygoogle = window.adsbygoogle || []).push({});

这个异常通常出现在使用Hibernate进行数据操作时,出现错误并且Session没有被关闭或者清理的情况下。

解决方案

1. 不要在try块中catch Exception

在Java编程中,我们一般会在try块中产生异常,并在catch块中进行处理。但是在使用Hibernate框架时,我们应该避免在try块中catch Exception异常。因为Hibernate会认为出现异常后,Session已经关闭,但实际上它没有关闭。

try {
    // .... 一些操作
} catch(Exception e) {
    // 不要在这里作处理
}

2. 错误处理后立即关闭Session

我们在数据操作遇到错误时,我们应该手动关闭Session或者使Session处于自动关闭状态。这样可以避免发生上述异常。

Session session = sessionFactory.openSession();
Transaction tx = null;
try {
    tx = session.beginTransaction();
    // ... 做一些操作
    tx.commit();
} catch (HibernateException e) {
    if (tx != null) tx.rollback();
    // 处理完后立即关闭Session
    session.close();
} finally {
    // 关闭Session
    session.close();
}

3. 不要在finally块中关闭Session

在finally块中关闭Session是一个常见的错误,因为有时finally块会在程序异常的情况下执行。如果此时Session已关闭,就会抛出上述异常。

Session session = sessionFactory.openSession();
Transaction tx = null;
try {
    tx = session.beginTransaction();
    // ... 做一些操作
    tx.commit();
} catch (HibernateException e) {
    if (tx != null) tx.rollback();
} finally {
    // 不要在这里关闭Session
}

总结

在使用Hibernate框架时,应该避免在try块中catch Exception异常,并手动关闭或自动关闭Session,避免在finally块中关闭Session,以避免出现上述异常。