Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Hibernate to read database and not return cached entity

I am using Hibernate and Spring for my web application.

In database operation, Hibernate is caching entities and returning them in next request without reading the actual database. I know this will reduce the load on database and improve performance.

But while this app still under construction, I need to load data from database in every request (testing reason).

Is there any way to force database read?

I became sure about the caching from this log4j message.

Returning cached instance of singleton bean 'HelloController' DEBUG [http-bio-8080-exec-42] - Last-Modified value for [/myApp/../somePageId.html] is: -1 
like image 239
Saif Avatar asked Jan 12 '15 15:01

Saif


People also ask

How do I invalidate cache in Hibernate?

But Hibernate invalidates the 2nd level cache if you execute an SQL UPDATE or DELETE statement as a native query. This is necessary because the SQL statement changed data in the database, and by that, it might have invalidated entities in the cache. By default, Hibernate doesn't know which records were affected.

Does Hibernate cache entities?

As with most other fully-equipped ORM frameworks, Hibernate has the concept of a first-level cache. It's a session scoped cache which ensures that each entity instance is loaded only once in the persistent context. Once the session is closed, the first-level cache is terminated as well.

Does Hibernate cache query results?

Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache. This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated.

Is second level caching mandatory in Hibernate?

You can extend this caching with an optional second-level cache. The first-level keeps being mandatory and is consulted first always. The second-level cache is used to cache object across sessions.


1 Answers

session.refresh(entity) or entityManager.refresh(entity) (if you use JPA) will give you fresh data from DB.

like image 62
Predrag Maric Avatar answered Sep 21 '22 10:09

Predrag Maric