本文共 1217 字,大约阅读时间需要 4 分钟。
Hibernate中持久化上下文的flush操作模式默认即为AUTO。在这种模式下,flush操作往往在如下场景下自动执行:
下面以JPA的EntityManager为例介绍flushMode="AUTO"的各个场景。
1.持久化上下文提交事务
entityManager = entityManagerFactory().createEntityManager();txn = entityManager.getTransaction();txn.begin();Person person = new Person( "John Doe" );entityManager.persist( person );//flush executedtxn.commit();
2.即将执行的HQL查询中涉及到了被缓冲的Entity对象
Person person = new Person( "John Doe" );entityManager.persist( person );entityManager.createQuery( "select p from Advertisement p" ).getResultList();//flush executedentityManager.createQuery( "select p from Person p" ).getResultList();
3.即将执行的native SQL查询中涉及到了被缓冲的Entity对象
在这种情况下,JPA的EntityManager将会无条件地执行flush操作,如下所示:
Person person = new Person( "John Doe" );entityManager.persist( person );entityManager.createNativeQuery("select count(*) from Person").getSingleResult();
但是,Hibernate的Session必须在如下情况下才执行flush操作:
Person person = new Person( "John Doe" );entityManager.persist( person );Session session = entityManager.unwrap(Session.class);session.createSQLQuery( "select count(*) from Person").addSynchronizedEntityClass(Person.class).uniqueResult();
转载地址:http://vilai.baihongyu.com/