查询后,EntityManager不刷新数据

Sat*_*tya 5 jpa hsqldb entitymanager jpa-2.0

我当前的项目使用HSQLDB2.0和JPA2.0.

该方案是:我查询数据库得到的名单contactDetailsperson.我contactInfo在UI处删除单个但不保存该数据(Cancel保存部分).

我再次执行相同的查询,现在结果列表比先前的结果小1,因为我在UI处删除了一个contactInfo.但contactInfo如果我交叉检查,那仍然可以在DB上找到.

但是如果我entityManager.clear()在查询开始之前包含,我每次都会得到正确的结果.

我不明白这种行为.有人能说清楚吗?

Lam*_*bda 16

而不是再次查询,试试这个:

entityManager.refresh(person);
Run Code Online (Sandbox Code Playgroud)

一个更完整的例子:

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();
Run Code Online (Sandbox Code Playgroud)