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