简体   繁体   English

Hibernate二级缓存——同一个实体的多个对象

[英]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.我正在测试 ehcache,但无法使其正常工作。 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: a) 使用一级缓存的示例,该缓存工作正常:

 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 b) 在 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它返回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.这不可能使用二级缓存在 Hibernate 的 RAM 中保留实体的一个实例,因为每次 Hibernate 在缓存中找到它时,它只会根据缓存的数据创建新实例。

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)出于我的目的,我实现了基于 AVL 树的加载实体和数据库同步引擎,该引擎基于从休眠中加载的实体创建存储库,并异步搜索实体中的所有字段并重写/合并所有相同的字段(以便如果某些字段(pk ) 与存储库中的实体相同,它取代了它)

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.通过这种方式,与数据库的同步很容易,因为它可以在存储库中找到外部更改的实体(因此基本上在 O(log n) 的 AVL 树中)并重写其字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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