Java 实体管理器如何读取其他人插入的新记录

Java 实体管理器如何读取其他人插入的新记录,java,hibernate,jpa,Java,Hibernate,Jpa,我的应用程序使用JPA/hibernate从数据库读取数据。应用程序是只读的,数据由其他程序插入 问题是我的应用程序只能在第一次读取肉体数据。当其他程序插入新数据时,我的应用程序无法看到它 以下是我的测试代码: public class TestJpaRead { private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");

我的应用程序使用JPA/hibernate从数据库读取数据。应用程序是只读的,数据由其他程序插入

问题是我的应用程序只能在第一次读取肉体数据。当其他程序插入新数据时,我的应用程序无法看到它

以下是我的测试代码:

public class TestJpaRead {
   private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");

   public static void main(String[] args) {
       LOG.debug("first time");
       countRow();   //output row size = X

       //set break point here, and manually insert an new row by using mysql client

       LOG.debug("second time");
       countRow();   //should output row size = X + 1, but it is still X
   }

   public static void countRow() {
       EntityManager em = emf.createEntityManager();
       Query query = em.createQuery("SELECT a FROM " + Report.class.getSimpleName() + " a");
       List result = query.getResultList();
       LOG.debug("countRow: {}", result.size());
       em.close();
   }
}
这是我的persistence.xml(没什么特别的):


Hibernate入门指南JPA教程的持久性单元
org.hibernate.ejb.HibernatePersistence


谢谢

从MySQL查询日志中,我找到了问题的原因:

                   48 Query SET autocommit=0
140606 11:35:41    48 Query select report0_.id from Report report0_  /*countRow()*/
                   48 Query SHOW WARNINGS
140606 11:35:42    48 Query select report0_.id from Report report0_  /*countRow()*/
                   48 Query SHOW WARNINGS
  • 默认情况下,Hibernate在自动提交模式下不工作

  • em.close()不隐式提交或回滚事务,即JDBC连接和事务仍然处于活动/打开状态。 这是我误解的。(emf.close()实际上会关闭连接。)

  • 当您从emf.createEntityManager()获取EntityManager时,新的 EntityManager可以重用旧的JDBC连接。这意味着你可以 在以前关闭的EntityManager打开的事务中

  • 当您处于未提交/打开的事务中时,请使用默认值 MySQL隔离级别,您无法看到其他人所做的更改


  • 解决方案:显式打开并提交事务,或者告诉Hibernate允许自动提交的JDBC连接。参考文献:

    mysql客户端的自动提交选项如何?数据库与用户会话一起工作,如果一个会话没有提交,其他会话将看不到修改。@JorgeCampos my mysql客户端使用默认的autocommit=true。我已经确认我可以通过另一个mysql客户端会话看到新记录。谢谢
                       48 Query SET autocommit=0
    140606 11:35:41    48 Query select report0_.id from Report report0_  /*countRow()*/
                       48 Query SHOW WARNINGS
    140606 11:35:42    48 Query select report0_.id from Report report0_  /*countRow()*/
                       48 Query SHOW WARNINGS