views:

163

answers:

2

for first level of cache, what i understand is when we do saveorupdate , we need to call flush() to refresh the cache in order for subsequent select query from DB. So, for application using hibernate, we should not modify records/delete records using DB-GUI without going through hibernate as the select will query wrong result because of cache. correct?

+3  A: 

Incorrect. The 1st-level cache is always consistent with itself, and consistent with updates made in that session. When the session is closed, all remaining updates are automatically flushed, you very rarely have to call flush() yourself.

Also, the 1st-level cache lasts only for the duration of the hibernate session (which generally only last for a couple of SQL statements, and typically lasts less than a second), so any updates made to the database directly will be reflected in the next hibernate session that gets started.

skaffman
how about for 2nd level cache. i'm sure if i modify directly records in DB, hibernate app will still be retriving from cache without knowing it?
cometta
Yes, that can be true for the L2 cache, but your question was talking about the L1 (session) cache. it's very important to distinguish the two, the behaviours are very different.
skaffman
And `CacheMode` is just for that.
Adeel Ansari
+1  A: 

Think if FlushMode is set to Auto, it should flush before making any HQL or criteria queries that could have been affected. If you are making SQL queries (or you are making HQL queries and FlushMode is not auto), you will need to flush or else the changes won't be reflected in the db when the SQL query occurs.

In addition, if you are not using a transaction you will need to call flush before disposing the session.

Check this out https://www.hibernate.org/hib%5Fdocs/v3/api/org/hibernate/FlushMode.html

mcintyre321