How to disable hibernate caching

后端 未结 7 1093
梦谈多话
梦谈多话 2020-11-30 03:04

I am trying to write a unit test class which will have to use same query to fetch the results from database two times in same test method. But as Hibernate cache is enabled

相关标签:
7条回答
  • 2020-11-30 03:39

    Use StatelessSession:

    http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/batch.html

    0 讨论(0)
  • 2020-11-30 03:40

    According to a guy from the hibenrate team :

    The second-level cache has nothing to do with the first-level (session or persistence context) cache. The persistence context/session cache is mandatory for various reasons. In fact, not understanding this crucial part and ignoring it in application architecture is a recipe for disaster. There is no quick solution here, study some documentation.

    Source :https://forum.hibernate.org/viewtopic.php?p=2383408
    You might use seesion.evict(your object) before retrying the same query.

    0 讨论(0)
  • 2020-11-30 03:44

    You can use:

    session.setCacheMode(CacheMode.IGNORE)

    after your:

    session.createQuery("from Table") statement.

    This will ensure that Hibernate doesn't interact with 2nd level cache for any entity returned by this query.

    0 讨论(0)
  • 2020-11-30 03:44

    If you create a new (different) session within your unit test, it will "not" use the old one's cache. Or if you call clear() on it first (another option), etc.

    0 讨论(0)
  • 2020-11-30 03:53

    Hibernate has two levels of Cache,

    1. Session cache (First level cache) is default cache and there is no mechanism to disable.

    2. SessionFactory (second level) level cache : We have to configure this in Hibernate cfg file by setting cache_provider.

      I had an requirement to load heavy data from DB, and I used stateless session because of following features.

       a. Stateless session does not support session cache and never interact with 
          second level cache.
       b. Stateless session does not support automatic dirty check.
       c. Stateless session does not support cascading to associated entities.
      

      Syntax to create Stateless session:

      StatelessSession statelessSession = sessionFactory.openStatelessSession();
      
    0 讨论(0)
  • 2020-11-30 03:57

    After the first time you query the result,call session.clear and then the same query will hit the database rather than level 1 cache

    0 讨论(0)
提交回复
热议问题