【发布时间】:2021-11-17 11:21:51
【问题描述】:
以下代码中的em.refresh(person) 不起作用。它不会使用数据库中的新值刷新person,而是重置(撤消或丢弃)缓存中所做的更改。我无法理解为什么?
em.getTransaction().begin();
Person person = em.find(Person.class, 2L); //Person[id=2L, age=23]
person.setAge(24);
System.out.println(person.getAge()); //it prints 24
//Person with id=2 in database gets modified concurrently somehow,
//its age becomes 25 in PERSON table (by an SQL update for example "UPDATE person SET age=25 WHERE id=2")
em.refresh(person); // attempts to load fresh value from database with a SELECT...
System.out.println(person.getAge()); //it prints 23, rather than 25, why?
em.getTransaction().commit();
em.close();
有人可以通过EntityManager 的refresh() 方法帮助我理解这种行为吗?
【问题讨论】:
-
刷新前可以使用flush吗?
-
您在事务中进行这些测试,事务通常带有“可重复读取”。除非数据库已更新(例如执行 flush ),否则它将在第二次选择时返回相同的值
-
@Alien 和 @Guillaume :在
em.refresh(person)之前发出em.flush()将发出UPDATE...更新数据库中的age=24,所以使用em.refresh(person)我不会得到age=25,我会得到它age=24。因此em.refresh(person)之前的em.flush()无助于从数据库中获取更新的数据。 -
@Guillaume
em.refresh(person)没有提供可重复读取,它正在撤消。它正在丢弃缓存中所做的更改(age从 23 更改为 24)并将person对象返回到它首次加载到缓存中时的状态(age=23)。所以em.refresh(person)也没有提供可重复读取,它正在重置/撤消person。 -
@skip 您确定更改
UPDATE person SET age=25 WHERE id=2已提交吗?顺便问一下,你用什么数据库?
标签: hibernate jpa entitymanager hibernate-jpa