Aleksey
Aleksey

Reputation: 1359

Hibernate cache level 1

I have one misunderstanding of cache level 1. So far I've seen that cache level 1 is used only to put off sql invocations until a transaction is flushed.

But what about objects? For instance, I use only cache level 1. If I were to load the same object several times within 1 transaction, what would happen? Does hibernate use some sort of identity map and caches objects which has been loaded within 1 transaction?

Upvotes: 3

Views: 1561

Answers (3)

J Jagadeesh Kumar
J Jagadeesh Kumar

Reputation: 31

Advantages of First Level caching over Second Level caching:

1.In First levlel caching the dirty read problem is removed .It means every time the object value is updated.

2.It reduces the number of round trips between client and DataBase.

Disadvantages of First Level caching over Second Level caching:

1.The object of first level caching is not sharable across sessions.

Upvotes: 3

Pascal Thivent
Pascal Thivent

Reputation: 570605

So far I've seen that cache level 1 is used only to put off sql invocations until a transaction is flushed.

To put it simply, the first level cache is just a map from id (primary key) to an object that holds the state associated with that primary key.

But you shouldn't mix session and transaction concepts, they are not the same thing (and a session is not necessarily transaction scoped).

If I were to load the same object several times within 1 transaction, what would happen?

There will be only one object representing a given row in the database (i.e. for a given id). That's what makes managing state possible and that's the whole point of the 1st level cache.

Does hibernate use some sort of identity map and caches objects which has been loaded within 1 transaction

See above.

Upvotes: 4

tucaz
tucaz

Reputation: 6684

You are correct about Identity Map. (N)Hibernate uses an identity map (http://martinfowler.com/eaaCatalog/identityMap.html) in order to keep the objects that it already loaded previously.

However, this cache is kept by ISession which means that you have to share the same ISession object in order to take advantage of this cache.

If you want your cache to be shared accross multiple ISession you should take a look at (N)Hibernate Cache Level 2.

Upvotes: 2

Related Questions