Enterprise Java Development@TOPIC@
void flush();
Synchronizes cached changes with underlying database
Requires active transaction
void setFlushMode(javax.persistence.FlushModeType);
javax.persistence.FlushModeType getFlushMode();
AUTO (default) - unspecified
COMMIT - flush only happens during commit
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
Updates/overwrites cached entity state with database state
Refresh of new entity results in java.lang.IllegalArgumentException
Author author = new Author();
author.setFirstName("test");
author.setLastName("new");
try {
em.refresh(author);
fail("refresh of new entity not detected");
} catch (IllegalArgumentException ex) {
logger.debug("caught expected exception:" + ex);
}
-caught expected exception:java.lang.IllegalArgumentException: Entity not managed
Refresh of detached entity results in java.lang.IllegalArgumentException
em.persist(author);
em.getTransaction().begin();
em.getTransaction().commit();
//refreshing a detached entity will get rejected
Author detached = new Author(author.getId());
em.refresh(author);
logger.debug("refreshed managed entity");
try {
em.refresh(detached);
fail("refresh of detached entity not detected");
} catch (IllegalArgumentException ex) {
logger.debug("caught expected exception:" + ex);
}
-refreshed managed entity -caught expected exception:java.lang.IllegalArgumentException: Entity not managed