Jpa Hibernate: Reading updated values problem

吃可爱长大的小学妹 提交于 2020-06-29 08:31:58

问题


I develop an project using JPA along with Hibernate and I have two threads:

  • Thread A: is always reading and outputs the differences
  • Thread B: has some write operations and one transaction which is committed after finishing writing data

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

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.

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?

Thank you.


回答1:


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.

Session acts as a transaction-level cache of persistent data. Once an entity becomes managed, that object is added to the internal cache of the current persistence context (EntityManager or Session). The persistence context is also called the first-level cache, and it’s enabled by default.

http://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#



来源:https://stackoverflow.com/questions/55279231/jpa-hibernate-reading-updated-values-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!