Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable hibernate caching

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 second time it is not actually hitting the database and simply fetching the results from cache.

Can someone please answer how to disable caching in persistence.xml.

I tried to disable by changing properties hibernate.cache.use.query_cache = false and hibernate.cache.use_second_level_cache = false.

But It did not work.

like image 849
Srinivas Avatar asked Sep 30 '10 04:09

Srinivas


People also ask

Can we disable Hibernate first level cache?

Hibernate comes with different types of Cache: First Level Cache: Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it.

Can we disable second level cache in Hibernate?

To disable second-level caching (say for debugging purposes), we just set the hibernate. cache. use_second_level_cache property to false.

Does Hibernate cache by default?

Hibernate uses first-level cache by default and you have nothing to do to use first-level cache. Let's go straight to the optional second-level cache. Not all classes benefit from caching, so it's important to be able to disable the second-level cache. The Hibernate second-level cache is set up in two steps.


1 Answers

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.

like image 189
Pascal Thivent Avatar answered Sep 20 '22 15:09

Pascal Thivent