How to disable hibernate caching
Solution 1:
Can someone please answer how to disable caching in persistence.xml.
The second-level cache and query cache are disabled by default (and queries are not cached unless you explicitly cache them). The first-level cache can't be disabled.
I tried to disable by changing properties (...)
This would disable the second-level cache and query cache, if they were enabled.
But It did not work.
To be honest, "it did not work" is a very poor description of the current behavior vs the expected one. Providing more details, (pseudo) code, SQL traces would probably help.
That being said, if the question is about HQL, an HQL query should definitely hit the database upon subsequent execution (without any query cache). Activate SQL logging if required to observe this.
If the question is about Session#get()
or Session#load()
, then you could reload the state of an entity using Session#refresh()
or call Session#clear()
to completely clear the session.
Solution 2:
Hibernate has two levels of Cache,
Session cache (First level cache) is default cache and there is no mechanism to disable.
-
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();
Solution 3:
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.
Solution 4:
Use StatelessSession:
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/batch.html
Solution 5:
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.