在Hibernate中持久化上下文的flush操作模式中,JPA还支持COMMIT(JPA只支持AUTO和COMMIT两种)。对于COMMIT的flush操作模式,JPA针对HQL查询和native SQL查询有不同的执行:
- 对于HQL查询,无论是否涉及到了被缓冲的Entity对象,都只会在当前事务提交的时候执行flush操作
- 对于native SQL查询,如果涉及到了被缓冲的Entity对象,将会执行flush操作
1.HQL查询
txn = entityManager.getTransaction();
txn.begin();
Person person = new Person("John Doe");
entityManager.persist(person);
entityManager.createQuery("select p from Advertisement p")
.setFlushMode( FlushModeType.COMMIT)
.getResultList();
entityManager.createQuery("select p from Person p")
.setFlushMode( FlushModeType.COMMIT)
.getResultList();
//flush executed
txn.commit();
2.native SQL查询
Person person = new Person("John Doe");
entityManager.persist(person);
//flush executed
entityManager.createNativeQuery("select count(*) from Person").setFlushMode( FlushModeType.COMMIT).getSingleResult();