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

时间:2012-03-06 15:54:25

标签: java hibernate orm

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

对我而言,这是一个很大的WTF:

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

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

很明显,如果父对象发生了变化,那么保留它的集合几乎没有意义,因为它们最有可能是从父节点派生出来的。

我在这里遗漏了什么吗?如果不手动编写所有这些代码,是否真的无法将对象与其所有子实体一起刷新?

2 个答案:

答案 0 :(得分:4)

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

hibernate.cache.auto_evict_collection_cache=true

只要不修复此修复程序,您就可以通过自己的SessionFactory和SessionFactoryServiceRegistry注册CollectionCacheInvalidator来解决驱逐逻辑。

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()
                )
        );
    }
}

答案 1 :(得分:0)

这只是一个缓存。缓存只是应该减少数据库访问。当你驱逐一个对象时,通常你没有对子对象进行任何修改,并且它们可以在下次从缓存中加载。此外,经常发生子对象仍被其他父对象使用(在这种情况下,名称'child'不正确,因为它是n:1或m:n关系)。驱逐儿童可能会在儿童物品仍在使用的其他地方引发非常奇怪的错误。

因此,如果将孩子驱逐出去只取决于你的应用程序和数据库设计。因此,默认情况下,hibernate不会驱逐子对象。

如果您希望自动驱逐子对象,请在映射文件中使用cascade =“evict”。

驱逐所有对象的更为狂暴的方法是关闭会话并打开一个新会话。然后,会话的所有对象都被逐出。