回滚和二级集合缓存
我有 Hibernate 和 Ehcache 提供的二级缓存。
我有 Parent
和 Child
类,以及 Parent.children
缓存集合。
当我执行以下代码时:
Session session = DataSessionFactory.openSession();
Transaction tx = session.beginTransaction();
Parent parent = // load from Session
Child child = new Child();
child.setParent(parent);
session.saveOrUpdate(child);
session.flush();
session.refresh(parent);
tx.rollback();
session.close();
session = DataSessionFactory.openSession();
tx = session.beginTransaction();
parent = session.load(Parent.class, parent.getId());
System.out.println(parent.getChildren());
最后一行失败并出现异常,尝试加载不存在的 Child
。经过调查,我发现原因是它试图加载在上一个事务中创建并回滚的 Child
。
配置缓存或回滚事务以便正确清除集合缓存的正确方法是什么?我不想在回滚时清除所有集合缓存,谢谢。寻找一种方法让 Hibernate 或 Ehcache 为我做这件事,影响最小。
I have Hibernate with 2nd level cache provided by Ehcache.
I have Parent
and Child
classes, with Parent.children
cached collection.
When I execute the following code:
Session session = DataSessionFactory.openSession();
Transaction tx = session.beginTransaction();
Parent parent = // load from Session
Child child = new Child();
child.setParent(parent);
session.saveOrUpdate(child);
session.flush();
session.refresh(parent);
tx.rollback();
session.close();
session = DataSessionFactory.openSession();
tx = session.beginTransaction();
parent = session.load(Parent.class, parent.getId());
System.out.println(parent.getChildren());
The last line fails with an exception, trying to load Child
which does not exist. After investigation I found the reason is that it's trying to load Child
which have been created and rolled back in the previous transaction.
What is the correct way to configure caching, or roll back the transaction, so that collection cache is cleared properly? I don't want to purge all collection caches on rollback, thank you. Looking for a way to make Hibernate or Ehcache do it for me with minimal impact.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Hibernate 事务管理器非常简单,从您的描述来看,它似乎无法处理这种情况。原因很简单:Hibernate 并不试图自己实现 JTA,因为有很多 JTA 提供程序。因此,如果您使用像 JBoss AS 这样的应用程序服务器,您可以配置 Hibernate 和 EHCache 以使用其 JTA 提供程序,这肯定可以处理这种情况。
另外,我相信该实体正在通过“刷新”方法放入缓存中。因此,如果您不想使用 JTA 提供程序,并且除非确实需要“刷新”,否则我会删除该部分。
The Hibernate transaction manager is quite simple and from what you described, it seems it doesn't handle this case. The reason is simple: Hibernate is not trying to implement JTA by itself, as there are plenty of JTA providers out there. So, if you are using an application server like JBoss AS, you can configure Hibernate and EHCache to use its JTA provider, which would certainly handle this situation.
Also, I believe that the entity is being put into the cache by the "flush" method. So, if you don't want to use a JTA provider and unless this "flush" is really needed, I'd remove that part.