首页 > 解决方案 > 如何在同一个休眠会话中从数据库表中获取更新的值

问题描述

我有一个结果表。我正在使用 result_id 获取结果行,然后使用结果详细信息。

我正在更新结果表的一些值:

try {
        Result instance = (Result) getTransactionSession().get("com.xxx.Result", id); //$NON-NLS-1$
        commit();

        if (instance == null) {
            ResultHome.log.debug("get successful, no instance found"); //$NON-NLS-1$
        } else {
            updateResultStepsSequence(id, instance);
            ResultHome.log.debug("get successful, instance found"); //$NON-NLS-1$
        }
        return instance;
    } catch (RuntimeException re) {
        ResultHome.log.error("get failed", re); //$NON-NLS-1$
        rollback();
        throw re;
    }

private void updateResultStepsSequence(long resultId, Result resultInstance) {
    if (resultInstance.getStepCount() > 0) {
        List<ResultStep> resultSteps = resultInstance.getResultSteps();
        if (resultSteps != null && !resultSteps.isEmpty() && (resultSteps.get(0).getDurationSum() == 0)) {
            try {
                Session session = SessionFactoryProvider.getSessionFactory().getCurrentSession();
                Query query = session.getNamedQuery("updateResultStepSequence").setLong("result_id", //$NON-NLS-1$ //$NON-NLS-2$
                        resultId);
                query.executeUpdate();
                commit();
            } catch (RuntimeException re) {
                ResultHome.log.error("Query execution failed", re); //$NON-NLS-1$
                rollback();
                throw re;
            }
        }
    }
}

执行 updateResultStepsSequence() 方法后,我可以看到表正在更新,但实例对象仍保留数据库更新之前的旧值。

如何从表中获取更新的值?我尝试创建一个新会话,更新表并关闭新创建的会话。

通过这种方法,我能够从表中获取最新的更新值。

有没有更好的方法来做到这一点?

标签: javahibernate

解决方案


Session.refresh()方法可用于从数据库中获取最新状态:

session.refresh(instance)

推荐阅读