Domanda

I have started learning about Hibernate Second level cache.

I tried with the following sample code for understanding Hibernate second level cache.

Session session = sessionFactory.openSession();
session.beginTransaction();
UserDetails u1 = (UserDetails) session.get(UserDetails.class,1);
session.getTransaction().commit();
session.close();
Session session2=sessionFactory.openSession();
session2.beginTransaction();
UserDetails u2 = (UserDetails) session2.get(UserDetails.class, 1);
session2.getTransaction().commit();
System.out.println(u1==u2);
session2.close();

I am reading the same UserDetails object(with '1' as id) in 2 different sessions. It should return the same object as i have enabled second level cache.

But when i compare both the objects,its showing 'false'.

Can some one let me know how hibernate second level cache works internally?

È stato utile?

Soluzione

The second-level cache doesn't store instances of your entity. It stores the contents of the row corresponding to this entity. And even if it stored entity instances, returning the same instances to different transactions would completely break your application: different transactions running in parallel would modify the same, non-thread-safe object, and you wouldn't have any isolation anymore between transactions.

So every transaction will always have a distinct entity instance, even if the second-level cache is used.

To check that the second cache is hit, enable SQL logging, and check that the query to load the data is executed once, and not twice.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top