gpt4 book ai didi

java - Hibernate 标准结果会在单个事务期间更新而无需 session 刷新吗?

转载 作者:行者123 更新时间:2023-11-30 03:49:19 26 4
gpt4 key购买 nike

无论出于何种原因,我有一个代码本质上执行如下所示的操作:它在单个事务/ session 中加载实例几次:

@Transactional
public void fun(final String someName){
for(int i=0; i<10; ++i) {
SomeClass someClass = (SomeClass) session()
.createCriteria(SomeClass.class)
.add(Restrictions.eq("name", someName))
.uniqueResult();

// when not found
if(someClass == null){
someClass = new SomeClass();
someClass.setName(someName); // it SHOULD be found in subsequent criteria calls
}

process(someClass);

session().saveOrUpdate(someClass);
// session.flush(); // should it be here?
}
}

我不确定的是 session().createCriteria... 调用的结果是否在循环期间发生变化。

它在事务中,如果我找不到实体 - 我会创建它(但仅一次)。

那么在第二遍期间,someClass 实例是否始终为非空?

最佳答案

当然你不必调用flush,你应该很少执行flush。然而,证明某些事情的最好方法是使用一个简单的演示,因此我编写了一个 Spring Boot/Data 示例并将其推送到 Github 。该代码与您的代码等效,并使用 Hibernate 4.3.5:

@Transactional
public void createOrUpdateEmployee(String firstName, String lastName) {
for (int i = 0; i < 10; i++) {
Employee employee = repository.findByLastName(lastName);
if (employee == null) {
employee = new Employee(firstName, lastName);
if (i > 0) {
throw new IllegalStateException("This can never happen!");
}
}

log.info(employee);

repository.save(employee);
}
}

输出为:

....350  ...EmployeeService      : Employee [id=0, firstName=Andreas, lastName=Kluth, hashCode=1686333223]
....396 ...EmployeeService : Employee [id=1, firstName=Andreas, lastName=Kluth, hashCode=1686333223]
....401 ...EmployeeService : Employee [id=1, firstName=Andreas, lastName=Kluth, hashCode=1686333223]
....403 ...EmployeeService : Employee [id=1, firstName=Andreas, lastName=Kluth, hashCode=1686333223]
....405 ...EmployeeService : Employee [id=1, firstName=Andreas, lastName=Kluth, hashCode=1686333223]
....407 ...EmployeeService : Employee [id=1, firstName=Andreas, lastName=Kluth, hashCode=1686333223]
....410 ...EmployeeService : Employee [id=1, firstName=Andreas, lastName=Kluth, hashCode=1686333223]
....412 ...EmployeeService : Employee [id=1, firstName=Andreas, lastName=Kluth, hashCode=1686333223]
....427 ...EmployeeService : Employee [id=1, firstName=Andreas, lastName=Kluth, hashCode=1686333223]
....429 ...EmployeeService : Employee [id=1, firstName=Andreas, lastName=Kluth, hashCode=1686333223]

正如我所期望的,该实体是从 L1 缓存中检索的(hashCode 保持不变)并自动刷新,正如已经提到的文档链接指出的那样:https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Web_Platform/5/html/Hibernate_Core_Reference_Guide/objectstate-flushing.html

关于java - Hibernate 标准结果会在单个事务期间更新而无需 session 刷新吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24825010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com