简体   繁体   中英

How can I stop Java or Hibernate Caching

I have an app to retrieve data from Database, and I monitor the time my app takes to retrieve data.

But I have an issue when I use the same data input set to retrieve data with my app, the second time retrieving will take much less time.

I assume Java or Hibernate has some cache or temp file to save the data, so second time run will be fast, but I don't want it happen. I need monitor the time it actually takes, not the time retrieve from cache or temp file.

I tried to forbid the cache and temp file generate in Java control Panel, I tried to disable the hibernate cache(first level or second level). But these are still not solve my problem. The second time run still takes less time than it should take.

Any idea the reason caused the second time run faster? it just a simple app to retrieve data from DB

The Hibernate 1st level cache can not be disabled (see How to disable hibernate caching ). You need to understand Hibernate's session cache if you want to force Hibernate querying to the database.

Lokesh Gupta has a good tutorial on http://howtodoinjava.com/2013/07/01/understanding-hibernate-first-level-cache-with-example/

  1. First level cache is associated with “session” object and other session objects in application can not see it.
  2. The scope of cache objects is of session. Once session is closed, cached objects are gone forever.
  3. First level cache is enabled by default and you can not disable it .
  4. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session.
  5. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.
  6. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method.
  7. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

You should therefor either use the evict() or clear() method to force a query to the database.

In order to verify this, you can turn on SQL output using the hibernate.show_sql configuration property (see https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/ch03.html#configuration-optional ).

Have you tried disabling the cache in the database itself?

I believe that Hibernate first and second level caches are Hibernate specific, but the database will still cache under the hood.

MySQL - force not to use cache for testing speed of query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM