开发者

Hibernate first level caching

开发者 https://www.devze.com 2023-02-24 05:43 出处:网络
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

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?


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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号