EntityManager doesn't refresh the data after querying

前端 未结 2 1531
离开以前
离开以前 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();
    
    0 讨论(0)
  • 2021-01-06 02:42

    The behaviour of clear() is explained in its javadoc:

    Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.

    That is, removal of contactInfo is not persisted.

    ContactInfo is not getting removed from the database because you remove the relationship between ContactDetails and ContactInfo, but not ContactInfo itself. If you want to remove it, you need either do it explicitly with remove() or specify orphanRemoval = true on the relationship.

    0 讨论(0)
提交回复
热议问题