java - 如何在同一个休眠会话中从数据库表中获取更新的值
问题描述
我有一个结果表。我正在使用 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() 方法后,我可以看到表正在更新,但实例对象仍保留数据库更新之前的旧值。
如何从表中获取更新的值?我尝试创建一个新会话,更新表并关闭新创建的会话。
通过这种方法,我能够从表中获取最新的更新值。
有没有更好的方法来做到这一点?
解决方案
Session.refresh()方法可用于从数据库中获取最新状态:
session.refresh(instance)
推荐阅读
- java - JUnit 如何在 Optional 和对象上断言 True/Equals
- angular - 如何在表单数组中添加无效的表单控件而不影响其功能
- python - 使用 Scrapy 和 CSS 选择器抓取整个页面
- numpy - 其他值的 trim_zeros 的 Numpy 等价物
- vim - 如何在 Vim 中阻止箭头键和鼠标?
- excel-formula - 根据 Criteria 计算出现次数
- javascript - HTML5 Canvas 如何绘制带渐变边框的松鼠?
- java - 从对象获取 JavaArray 属性
- java - (随机选择)文件中的名称
- php - 如何修复 linux php 中缓慢的 PDO mssql 连接?