问题描述
我与Hibernate一起使用JPA开发了一个项目,并且有两个线程:
I develop an project using JPA along with Hibernate and I have two threads:
- 线程A:始终在读取并输出差异
- 线程B:具有一些写操作和一个事务,该事务在完成数据写入后被提交
如果我从线程B中删除数据或在数据库中插入新数据,则在从线程B提交事务之后,在线程A中我看到了区别,即某些数据已被删除或添加.我的问题是何时更新现有数据:提交后,线程A看不到差异,除非每次读取后都没有清除EntityManager.
If I delete data or insert new data from/in the database, after committing transactions from Thread B, in Thread A I see the differences, that some data was removed or added.My problem is when I update existing data: after committing, Thread A doesn't see the differences, unless I'm not clearing the EntityManager after each read.
这些是放置在实体管理器上的属性:
Those are the properties put on the entity manager:
EntityManager em = EMF.createEntityManager();
em.setProperty("hibernate.connection.autocommit", false);
em.setProperty("hibernate.connection.isolation", 2); // read committed
em.setProperty("javax.persistence.cache.storeMode", javax.persistence.CacheStoreMode.BYPASS);
em.setProperty("javax.persistence.cache.retrieveMode", javax.persistence.CacheRetrieveMode.BYPASS);
em.setProperty("hibernate.cache.use_query_cache", false);
em.setProperty("hibernate.cache.use_second_level_cache", false);
另一件事是我将记录器配置为波纹管:
Another thing is that I configured the logger as bellow:
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
向我显示所有sql和设置/返回的值.我观察到,在第一次读取时,它从数据库中读取每个值,第二次读取后,如果要插入数据,则仅读取id和新插入的值...但是更新时看起来没有什么不同.
to show me all sql and setted/returrned values. I observed that at the first read, it reads every single value from the database and after second time reads just the ids and new inserted values in case of inserting data... but nothing looks different when it about the updates.
因此,考虑到我没有使用Hibernate的二级缓存,并且绕过了会话缓存的存储和检索模式,由于我不了解并且无法解决该问题,所以更确切地发生了什么每次读取后的持久性上下文?
So, considering that I'm not using the Hibernate's second level cache and that I bypass the store and retrieve mode for the session cache, whats happens more exactly because I can't understand and how I can fix this problem without clearing the persistence context after each read?
谢谢.
推荐答案
默认情况下,Hibernate中禁用二级缓存(其属性不适用).您在这里处理一级缓存.它在休眠会话期间存在.
Second level cache is disabled by default in Hibernate(properties for it are not applicable). You are dealing here with first level cache. It exists during the Hibernate session.
http://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#
这篇关于Jpa Hibernate:读取更新的值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!