EntityManager在查询后不刷新数据 [英] EntityManager doesn't refresh the data after querying
问题描述
我当前的项目使用HSQLDB2.0和JPA2.0.
My current project uses HSQLDB2.0 and JPA2.0 .
方案是:我查询数据库以获取person
的contactDetails
的列表.我在用户界面上删除了一个contactInfo
,但不保存该数据(取消保存部分).
The scenario is: I query DB to get list of contactDetails
of person
. I delete single contactInfo
at UI but do not save that data (Cancel the saving part).
我再次执行相同的查询,现在结果列表比以前的结果小1,因为我在UI上删除了一个contactInfo.但是,如果我进行交叉检查,该contactInfo
在DB上仍然可用.
I again do the same query, now the result list is 1 lesser than previous result coz I have deleted one contactInfo at UI. But that contactInfo
is still available at DB if I cross check.
但是,如果我在查询开始前加入entityManager.clear()
,则每次都会得到正确的结果.
But if I include entityManager.clear()
before start of the query, I get correct results every time.
我不了解这种行为.有人可以为我说清楚吗?
I dont understand this behaviour. Could anyone make it clear for me?
推荐答案
而不是再次查询,请尝试以下操作:
Rather than querying again, try this:
entityManager.refresh(person);
更完整的示例:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("...");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Person p = (Person) em.find(Person.class, 1);
assertEquals(10, p.getContactDetails().size()); // let's pretend p has 10 contact details
p.getContactDetails().remove(0);
assertEquals(9, p.getContactDetails().size());
Person p2 = (Person) em.find(Person.class, 1);
assertTrue(p == p2); // We're in the same persistence context so p == p2
assertEquals(9, p.getContactDetails().size());
// In order to reload the actual patients from the database, refresh the entity
em.refresh(p);
assertTrue(p == p2);
assertEquals(10, p.getContactDetails().size());
assertEquals(10, p2.getContactDetails().size());
em.getTransaction().commit();
em.close();
factory.close();
这篇关于EntityManager在查询后不刷新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!