Enterprise Java Development@TOPIC@

Chapter 41. Entity Manager State Synchronization Methods

41.1. flush()
41.2. FlushMode
41.3. refresh()


void flush();
        


void setFlushMode(javax.persistence.FlushModeType);
javax.persistence.FlushModeType getFlushMode();
        


em.persist(author);
em.getTransaction().begin();
em.getTransaction().commit();
//change DB state out-of-band from the cache
em.getTransaction().begin();
String newName="foo";
int count=em.createQuery(
        "update jpaAuthor a set a.firstName=:name where a.id=:id")
    .setParameter("id", author.getId())
    .setParameter("name", newName)
    .executeUpdate();
em.getTransaction().commit();
assertEquals("unexpected count", 1, count);
//object state becomes stale when DB changed out-of-band
logger.debug("author.firstName={}", author.getFirstName());
assertNotEquals("unexpected name", newName, author.getFirstName());
//get the cached object back in sync
logger.debug("calling refresh");
em.refresh(author);
logger.debug("author.firstName=" + author.getFirstName());
assertEquals("unexpected name", newName, author.getFirstName());
-author.firstName=dr
-calling refresh
-author.firstName=foo