EntityManager doesn't refresh the data after querying

前端 未结 2 1530
离开以前
离开以前 2021-01-06 01:39

My current project uses HSQLDB2.0 and JPA2.0 .

The scenario is: I query DB to get list of contactDetails of person. I delete single c

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-06 02:36

    Rather than querying again, try this:

    entityManager.refresh(person);
    

    A more complete example:

    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();
    

提交回复
热议问题