gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:22:40 24 4
gpt4 key购买 nike

我刚刚意识到,当一个对象从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com