草庐IT

java - 与父实体一起驱逐依赖集合

coder 2024-04-01 原文

我刚刚意识到,当一个对象从 Hibernate 缓存中被逐出时,dependant collections, if cached, have to be evicted separately .

对我来说,这是一个很大的 WTF:

  • 很容易忘记驱逐一个集合(例如,当一个新的集合被添加到对象映射时);
  • 驱逐依赖集合的代码丑陋且庞大,例如

    MyClass myObject = ...;
    getHibernateTemplate().evict(myObject);
    缓存 cache = getHibernateTemplate().getSessionFactory().getCache();
    cache.evictCollection("my.package.MyClass.myCollection1, id);
    ...
    cache.evictCollection("my.package.MyClass.myCollectionN, id);

很明显,如果父对象发生了变化,那么保留它的集合就没有什么意义了,因为它们最有可能派生自该父对象。

我是不是漏掉了什么?如果不手动编写所有这些代码,真的没有办法将一个对象及其所有子实体一起刷新吗?

最佳答案

这是一个旧的issue .有一种方法可以挂接到 hibernate 以在插入、更新或删除集合引用实体时驱逐集合缓存。我有 supplied a fix for hibernate .该修复计划用于 Hibernate 4.3.0.Beta5,并将由属性激活:

hibernate.cache.auto_evict_collection_cache=true

只要此修复程序未发布,您就可以解决注入(inject)逐出逻辑的问题,方法是自行将 CollectionCacheInvalidator 注册到您的 SessionFactory 和 SessionFactoryServiceRegistry。

import javax.persistence.OneToMany;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import my.own.library.BeanInformationFromClass;
import my.own.library.PropertyInformationFromClass;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventSource;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.PostInsertEvent;
import org.hibernate.event.spi.PostInsertEventListener;
import org.hibernate.event.spi.PreDeleteEvent;
import org.hibernate.event.spi.PreDeleteEventListener;
import org.hibernate.event.spi.PreUpdateEvent;
import org.hibernate.event.spi.PreUpdateEventListener;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.Joinable;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;

/**
 * @author Andreas Berger (latest modification by $Author$)
 * @version $Id$
 * @created 27.08.13 - 17:49
 */
public class CollectionCacheInvalidator
        implements PostInsertEventListener, PreDeleteEventListener, PreUpdateEventListener {

    private static final Logger LOGGER = Logger.getLogger( CollectionCacheInvalidator.class );

    private Map<String, String> mappedByFieldMapping;

    public void integrate(SessionFactoryImplementor sf, SessionFactoryServiceRegistry registry) {
        EventListenerRegistry eventListenerRegistry = registry.getService( EventListenerRegistry.class );
        eventListenerRegistry.appendListeners( EventType.POST_INSERT, this );
        eventListenerRegistry.appendListeners( EventType.PRE_DELETE, this );
        eventListenerRegistry.appendListeners( EventType.PRE_UPDATE, this );

        mappedByFieldMapping = new HashMap<String, String>();

        Map<String, CollectionPersister> persiters = sf.getCollectionPersisters();
        if ( persiters != null ) {
            for ( CollectionPersister collectionPersister : persiters.values() ) {
                if ( !collectionPersister.hasCache() ) {
                    continue;
                }
                if ( !(collectionPersister instanceof Joinable) ) {
                    continue;
                }
                String oneToManyFieldName = collectionPersister.getNodeName();
                EntityPersister ownerEntityPersister = collectionPersister.getOwnerEntityPersister();
                Class ownerClass = ownerEntityPersister.getMappedClass();

                // Logic to get the mappedBy attribute of the OneToMany annotation.
                BeanInformationFromClass bi = new BeanInformationFromClass( ownerClass );
                PropertyInformationFromClass prop = bi.getProperty( oneToManyFieldName );
                OneToMany oneToMany = prop.getAnnotation( OneToMany.class );
                String mappedBy = null;
                if ( oneToMany != null && StringUtils.isNotBlank( oneToMany.mappedBy() ) ) {
                    mappedBy = oneToMany.mappedBy();
                }
                mappedByFieldMapping.put( ((Joinable) collectionPersister).getName(), mappedBy );
            }
        }
    }

    @Override
    public void onPostInsert(PostInsertEvent event) {
        evictCache( event.getEntity(), event.getPersister(), event.getSession(), null );
    }

    @Override
    public boolean onPreDelete(PreDeleteEvent event) {
        evictCache( event.getEntity(), event.getPersister(), event.getSession(), null );
        return false;
    }

    @Override
    public boolean onPreUpdate(PreUpdateEvent event) {
        evictCache( event.getEntity(), event.getPersister(), event.getSession(), event.getOldState() );
        return false;
    }

    private void evictCache(Object entity, EntityPersister persister, EventSource session, Object[] oldState) {
        try {
            SessionFactoryImplementor factory = persister.getFactory();

            Set<String> collectionRoles = factory.getCollectionRolesByEntityParticipant( persister.getEntityName() );
            if ( collectionRoles == null || collectionRoles.isEmpty() ) {
                return;
            }
            for ( String role : collectionRoles ) {
                CollectionPersister collectionPersister = factory.getCollectionPersister( role );
                if ( !collectionPersister.hasCache() ) {
                    continue;
                }
                if ( !(collectionPersister instanceof Joinable) ) {
                    continue;
                }
                String mappedBy = mappedByFieldMapping.get( ((Joinable) collectionPersister).getName() );
                if ( mappedBy != null ) {
                    int i = persister.getEntityMetamodel().getPropertyIndex( mappedBy );
                    Serializable oldId = null;
                    if ( oldState != null ) {
                        oldId = session.getIdentifier( oldState[i] );
                    }
                    Object ref = persister.getPropertyValue( entity, i );
                    Serializable id = null;
                    if ( ref != null ) {
                        id = session.getIdentifier( ref );
                    }
                    if ( id != null && !id.equals( oldId ) ) {
                        evict( id, collectionPersister, session );
                        if ( oldId != null ) {
                            evict( id, collectionPersister, session );
                        }
                    }
                }
                else {
                    LOGGER.debug( "Evict CollectionRegion " + role );
                    collectionPersister.getCacheAccessStrategy().evictAll();
                }
            }
        }
        catch (Exception e) {
            LOGGER.error( "", e );
        }
    }

    private void evict(Serializable id, CollectionPersister collectionPersister, EventSource session) {
        LOGGER.debug( "Evict CollectionRegion " + collectionPersister.getRole() + " for id " + id );
        collectionPersister.getCacheAccessStrategy().evict(
                session.generateCacheKey(
                        id,
                        collectionPersister.getKeyType(),
                        collectionPersister.getRole()
                )
        );
    }
}

关于java - 与父实体一起驱逐依赖集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9587169/

有关java - 与父实体一起驱逐依赖集合的更多相关文章

  1. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. ruby-on-rails - 在 ruby​​ .gemspec 文件中,如何指定依赖项的多个版本? - 2

    我正在尝试修改当前依赖于定义为activeresource的gem:s.add_dependency"activeresource","~>3.0"为了让gem与Rails4一起工作,我需要扩展依赖关系以与activeresource的版本3或4一起工作。我不想简单地添加以下内容,因为它可能会在以后引起问题:s.add_dependency"activeresource",">=3.0"有没有办法指定可接受版本的列表?~>3.0还是~>4.0? 最佳答案 根据thedocumentation,如果你想要3到4之间的所有版本,你可以这

  4. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  5. ruby-on-rails - 如果我将 ruby​​ 版本 2.5.1 与 rails 版本 2.3.18 一起使用会怎样? - 2

    如果我使用ruby​​版本2.5.1和Rails版本2.3.18会怎样?我有基于rails2.3.18和ruby​​1.9.2p320构建的rails应用程序,我只想升级ruby的版本,而不是rails,这可能吗?我必须面对哪些挑战? 最佳答案 GitHub维护apublicfork它有针对旧Rails版本的分支,有各种变化,它们一直在运行。有一段时间,他们在较新的Ruby版本上运行较旧的Rails版本,而不是最初支持的版本,因此您可能会发现一些关于需要向后移植的有用提示。不过,他们现在已经有几年没有使用2.3了,所以充其量只能让更

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  8. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  9. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  10. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

随机推荐