我想在实体中应用外部更改。所以我在 EntityManager 中使用了 refresh()
它在 EntityManager session 中工作。但它在外部变化中不起作用。
它基于 SpringBoot 2.x。
这是我的简单代码。
@ExtendWith(SpringExtension.class)
@SpringBootTest
class RewardOrderRepositoryTest {
@Inject
private TestRepository testRepository;
@PersistenceContext
private EntityManager entityManager;
@Test
@Transactional
@Rollback(false)
public void test() {
final Test test = testRepository.findById(8L).get();
assertThat(test.getName(), is("Tom"));
// BREAK POINT : name modify to external mysql client(ex) mysql workbench)
entityManager.refresh(test);
assertThat(test.getName(), is("Alice")); // it's false, still Tom.
}
}
为什么没有反射(reflect)外部变化?
refresh() 方法仅在 EntityManager Session 中使用吗?
最佳答案
这是由事务隔离级别引起的 - MySQL 的默认值为 REPEATABLE READ :
This is the default isolation level for InnoDB. Consistent reads within the same transaction read the snapshot established by the first read. This means that if you issue several plain (nonlocking) SELECT statements within the same transaction, these SELECT statements are consistent also with respect to each other.
测试已经启动了一个事务,因此即使它们在不同的事务中被更改,它也会读取相同的数据。
您应该能够通过显式设置隔离级别来获得所需的行为:
@Transactional(isolation=Isolation.ISOLATION_READ_COMMITTED)
未在测试方法上进行测试:
isolation
根据 TransactionalTestExecutionListener
的 javadoc,测试方法似乎不支持该属性.
关于java - Spring Data Jpa EntityManager 刷新不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60505343/