Why does JPA EntityManager
execute a mutable query e.g. UPDATE
against DB directly, but choose to execute a SELECT
query first against the persistence context (aka second-level cache) below (tested with Hibernate 5
)?
It doesn't seem the JPA spec has prescribed to do so. Is it simply to gain better performance at risk of inconsistency?
/* ... */
String name = em.find(Person.class, 1).getName();
em.getTransaction().begin();
em.createQuery("update Person set name='new' where id=1")
.executeUpdate();
em.getTransaction().commit(); // DB updated but the entity not
Person p = em
.createQuery("select p from Person p where id=1", Person.class)
.getSingleResult(); // the stale entity returned
assertEqual(name, p.getName()); // true