简体   繁体   中英

Hibernate second level cache - multiple objects of the same entity

I need to ensure that only one object of the same entity is created (as it is done when loading data using first level hibernate cache, to simplify entity refreshing) and I want to use second level cache.

Im testing ehcache but cant make it working. Normally the entities in my app are being nested in other entities but this is just an simple example of usage:

a) example using first level cache which works fine:

 session = HibernateUtil.getSessionFactory().openSession();
 transaction = session.getTransaction();
 transaction.begin();
 Person person=session.get(Person.class, 1L);
 Person person2=session.get(Person.class, 1L);
 transaction.commit();
 session.close();

 System.out.println(person2 == person);

and it returns true

b) using second level cache with Ehcache

//1. load person with id 1
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.getTransaction();
transaction.begin();
Person person=session.get(Person.class, 1L);
transaction.commit();
session.close();

//2. load the same person
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.getTransaction();
transaction.begin();
Person person2=session.get(Person.class, 1L);
transaction.commit();
session.close();

System.out.println(person2 == person);

and it returns false

Is it normal behaviour of second level cache to be like that or do i miss something? Does any second level cache engine keep only one instance of the same entity (as first level cache do)?

This is not possible to keep one instance of the entity in RAM in Hibernate using second level cache as each time Hibernate find it in the cache, it just creates new instance based on the cached data.

For my purpose I have implemented AVL Tree based loaded entities and database synchronization engine that creates repositiories based on the loaded entities from hibernate and asynchronously search throught all the fields in entities and rewrites/merge all the same fields (so that if some field (pk) is the same entity like the one in repository, it replaces it)

In this way synchronization with database is easy as it comes to find the externally changed entity in the repository (so basically in the AVL Tree which is O(log n)) and rewrite its fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM