jhow
jhow

Reputation: 1

Hibernate first level caching

I want to know how load and get works with first level caching.

If I have a select query with in the same session with first retrieving using getmethod and then using load method. Will the 2nd load method use the query cache or will make a new query on retrieval of properties?

Upvotes: 0

Views: 1869

Answers (4)

Sk Sharma
Sk Sharma

Reputation: 131

First-level cache: It is at the transaction level and enabled by default in Hibernate. Caching at the first level is associated with a session. If the same query is executed multiple times in the same session, the data associated with the query is cached.

http://webiwip.com/interview-questions-answers/hibernate-interview-questions/32011

Upvotes: 0

neel4soft
neel4soft

Reputation: 537

First Level Caching is enabled by default and we don’t need to do anything to achieve it, in fact we can’t even disable it from there. First level caching is also called Session Level Caching meaning that it works for a session only, in case same query is being executed two or more times in a single session it gets data from the DB for the very first request only and serves the same data from cache for all upcoming similar requests.

More details : http://www.beingjavaguys.com/2014/11/how-first-level-caching-works-in.html

Upvotes: 0

Souvik Pal
Souvik Pal

Reputation: 35

I am newbie to hibernate. So to understand hibernate caching strategies I set up a line breakpoint at get and followed the call stack.

In the file StatefulPersistanceContext.java there are few maps e.g. entitiesByKey, which acts as session level cache. When you call get() it first checks the session level cache, if it misses, then checks the 2nd level cache (if that is set to use for that entity) otherwise it falls back to database. See doLoad() function and calls to loadFromSessionCache(), loadFromSecondLevelCache() and loadFromDatasource() in DefaultLoadEventListners.java file.

Once it retrieves rows from database it also populates the session level cache. So your subsequent calls to get() will be resolved from the session level cache itself.

Upvotes: 0

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

The cache is primary used when:

  • calling session.get
  • calling session.load
  • when (lazy) loading many-to-one and one-to-one relations

If there isn't a hit, get performs a query, load creates a proxy.

When performing any kind of query (HQL, criteria), the query is translated to SQL and performed on the database. If the resulting objects are found in the cache, the query will return them.

Upvotes: 3

Related Questions