HHH-7495 HHH-7492 Move RegionFactory to session factory scope service registry

This commit is contained in:
Strong Liu 2012-08-01 04:28:55 +08:00
parent 9632e010e8
commit 7f3ad01b50
69 changed files with 1148 additions and 1106 deletions

View File

@ -27,6 +27,7 @@
import org.hibernate.cache.CacheException;
import org.hibernate.cache.NoCacheRegionFactoryAvailableException;
import org.hibernate.cache.spi.AbstractRegionFactory;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.CollectionRegion;
import org.hibernate.cache.spi.EntityRegion;
@ -42,48 +43,48 @@
*
* @author Steve Ebersole
*/
public class NoCachingRegionFactory implements RegionFactory {
public class NoCachingRegionFactory extends AbstractRegionFactory {
public static RegionFactory INSTANCE = new NoCachingRegionFactory();
public NoCachingRegionFactory() {
}
public void start(Settings settings, Properties properties) throws CacheException {
@Override
public void start() {
}
@Override
public void stop() {
}
@Override
public boolean isMinimalPutsEnabledByDefault() {
return false;
}
@Override
public AccessType getDefaultAccessType() {
return null;
}
@Override
public long nextTimestamp() {
return System.currentTimeMillis() / 100;
}
@Override
public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
@Override
public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
@Override
public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
@Override
public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
@Override
public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}

View File

@ -29,24 +29,28 @@
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.metamodel.spi.source.MetadataImplementor;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
import org.hibernate.service.spi.BasicServiceInitiator;
import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.service.spi.SessionFactoryServiceInitiator;
/**
* Initiator for the {@link RegionFactory} service.
*
* @author Hardy Ferentschik
*/
public class RegionFactoryInitiator implements BasicServiceInitiator<RegionFactory> {
public class RegionFactoryInitiator implements SessionFactoryServiceInitiator<RegionFactory> {
public static final RegionFactoryInitiator INSTANCE = new RegionFactoryInitiator();
public static final String DEF_CACHE_REG_FACTORY = NoCachingRegionFactory.class.getName();
private static final String DEFAULT_IMPL = NoCachingRegionFactory.class.getName();
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
RegionFactoryInitiator.class.getName()
@ -63,43 +67,60 @@ public Class<RegionFactory> getServiceInitiated() {
}
@Override
@SuppressWarnings( { "unchecked" })
public RegionFactory initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
final Object impl = configurationValues.get( IMPL_NAME );
boolean isCacheEnabled = isCacheEnabled(registry);
if(!isCacheEnabled){
LOG.debugf( "Second level cache has been disabled, so using % as cache region factory", NoCachingRegionFactory.class.getName() );
return NoCachingRegionFactory.INSTANCE;
public RegionFactory initiateService(SessionFactoryImplementor sessionFactory, Configuration configuration, ServiceRegistryImplementor registry) {
return initiateService(sessionFactory, registry);
}
@Override
public RegionFactory initiateService(SessionFactoryImplementor sessionFactory, MetadataImplementor metadata, ServiceRegistryImplementor registry) {
return initiateService(sessionFactory, registry);
}
private RegionFactory initiateService(SessionFactoryImplementor sessionFactory, ServiceRegistryImplementor registry){
final Object impl = registry.getService( ConfigurationService.class ).getSettings().get( IMPL_NAME );
boolean isCacheEnabled = isCacheEnabled( registry );
RegionFactory factory;
if ( !isCacheEnabled ) {
LOG.debugf(
"Second level cache has been disabled, so using % as cache region factory",
NoCachingRegionFactory.class.getName()
);
factory = NoCachingRegionFactory.INSTANCE;
}
if ( impl == null ) {
else if ( impl == null ) {
LOG.debugf(
"No 'hibernate.cache.region.factory_class' is provided, so using %s as default",
NoCachingRegionFactory.class.getName()
);
return NoCachingRegionFactory.INSTANCE;
}
LOG.debugf( "Cache region factory : %s", impl.toString() );
if ( getServiceInitiated().isInstance( impl ) ) {
return (RegionFactory) impl;
}
Class<? extends RegionFactory> customImplClass = null;
if ( Class.class.isInstance( impl ) ) {
customImplClass = (Class<? extends RegionFactory>) impl;
factory = NoCachingRegionFactory.INSTANCE;
}
else {
customImplClass = registry.getService( ClassLoaderService.class )
.classForName( mapLegacyNames( impl.toString() ) );
LOG.debugf( "Cache region factory : %s", impl.toString() );
if ( getServiceInitiated().isInstance( impl ) ) {
factory = (RegionFactory) impl;
}
else {
Class<? extends RegionFactory> customImplClass = null;
if ( Class.class.isInstance( impl ) ) {
customImplClass = (Class<? extends RegionFactory>) impl;
}
else {
customImplClass = registry.getService( ClassLoaderService.class )
.classForName( mapLegacyNames( impl.toString() ) );
}
try {
factory = customImplClass.newInstance();
}
catch ( Exception e ) {
throw new ServiceException(
"Could not initialize custom RegionFactory impl [" + customImplClass.getName() + "]", e
);
}
}
}
try {
return customImplClass.newInstance();
}
catch ( Exception e ) {
throw new ServiceException(
"Could not initialize custom RegionFactory impl [" + customImplClass.getName() + "]", e
);
}
return factory;
}
private static boolean isCacheEnabled(ServiceRegistryImplementor serviceRegistry) {
@ -111,7 +132,8 @@ private static boolean isCacheEnabled(ServiceRegistryImplementor serviceRegistry
);
final boolean useQueryCache = configurationService.getSetting(
AvailableSettings.USE_QUERY_CACHE,
StandardConverters.BOOLEAN
StandardConverters.BOOLEAN,
false
);
return useSecondLevelCache || useQueryCache;
}

View File

@ -38,10 +38,15 @@
import org.hibernate.cache.spi.QueryCache;
import org.hibernate.cache.spi.QueryKey;
import org.hibernate.cache.spi.QueryResultsRegion;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.UpdateTimestampsCache;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Settings;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper;
@ -64,28 +69,30 @@ public class StandardQueryCache implements QueryCache {
private QueryResultsRegion cacheRegion;
private UpdateTimestampsCache updateTimestampsCache;
public void clear() throws CacheException {
cacheRegion.evictAll();
}
public StandardQueryCache(
final Settings settings,
final Properties props,
final UpdateTimestampsCache updateTimestampsCache,
String regionName) throws HibernateException {
public StandardQueryCache(SessionFactoryImplementor sessionFactoryImplementor, UpdateTimestampsCache updateTimestampsCache, String regionName) {
if ( regionName == null ) {
regionName = StandardQueryCache.class.getName();
}
String prefix = settings.getCacheRegionPrefix();
String prefix = sessionFactoryImplementor.getServiceRegistry()
.getService( ConfigurationService.class )
.getSetting(
AvailableSettings.CACHE_REGION_PREFIX, StandardConverters.STRING, null
);
if ( prefix != null ) {
regionName = prefix + '.' + regionName;
}
LOG.startingQueryCache( regionName );
this.cacheRegion = settings.getRegionFactory().buildQueryResultsRegion( regionName, props );
this.cacheRegion = sessionFactoryImplementor.getServiceRegistry()
.getService( RegionFactory.class )
.buildQueryResultsRegion( regionName, sessionFactoryImplementor.getProperties() );
this.updateTimestampsCache = updateTimestampsCache;
}
public void clear() throws CacheException {
cacheRegion.evictAll();
}
@SuppressWarnings({ "UnnecessaryBoxing", "unchecked" })
public boolean put(
QueryKey key,

View File

@ -23,13 +23,12 @@
*/
package org.hibernate.cache.internal;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.cache.spi.QueryCache;
import org.hibernate.cache.spi.QueryCacheFactory;
import org.hibernate.cache.spi.UpdateTimestampsCache;
import org.hibernate.cfg.Settings;
import org.hibernate.engine.spi.SessionFactoryImplementor;
/**
* Standard Hibernate implementation of the QueryCacheFactory interface. Returns instances of
@ -37,11 +36,8 @@
*/
public class StandardQueryCacheFactory implements QueryCacheFactory {
@Override
public QueryCache getQueryCache(
final String regionName,
final UpdateTimestampsCache updateTimestampsCache,
final Settings settings,
final Properties props) throws HibernateException {
return new StandardQueryCache(settings, props, updateTimestampsCache, regionName);
public QueryCache getQueryCache(String regionName, UpdateTimestampsCache updateTimestampsCache, SessionFactoryImplementor sessionFactoryImplementor)
throws HibernateException {
return new StandardQueryCache( sessionFactoryImplementor, updateTimestampsCache, regionName );
}
}

View File

@ -0,0 +1,51 @@
package org.hibernate.cache.spi;
import java.util.Properties;
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Settings;
import org.hibernate.cfg.SettingsFactory;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
import org.hibernate.service.spi.ServiceRegistryAwareService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
* @author Strong Liu <stliu@hibernate.org>
*/
public abstract class AbstractRegionFactory implements RegionFactory, ServiceRegistryAwareService {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
AbstractRegionFactory.class.getName()
);
private ServiceRegistryImplementor serviceRegistry;
private boolean isMinimalPutsEnabled;
public ServiceRegistryImplementor getServiceRegistry() {
return serviceRegistry;
}
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
this.serviceRegistry = serviceRegistry;
this.isMinimalPutsEnabled = serviceRegistry.getService( ConfigurationService.class ).getSetting( AvailableSettings.USE_MINIMAL_PUTS,
StandardConverters.BOOLEAN, isMinimalPutsEnabledByDefault()
);
LOG.debugf( "Optimize cache for minimal puts: %s", SettingsFactory.enabledDisabled( isMinimalPutsEnabled ) );
}
@Override
public void start(Settings settings, Properties properties) throws CacheException {
start();
}
@Override
public boolean isMinimalPutsEnabled() {
return isMinimalPutsEnabled;
}
}

View File

@ -23,10 +23,8 @@
*/
package org.hibernate.cache.spi;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Settings;
import org.hibernate.engine.spi.SessionFactoryImplementor;
/**
* Defines a factory for query cache instances. These factories are responsible for
@ -36,8 +34,7 @@
*/
public interface QueryCacheFactory {
public QueryCache getQueryCache(
String regionName,
UpdateTimestampsCache updateTimestampsCache,
Settings settings,
Properties props) throws HibernateException;
String regionName,
UpdateTimestampsCache updateTimestampsCache,
SessionFactoryImplementor sessionFactoryImplementor) throws HibernateException;
}

View File

@ -29,6 +29,8 @@
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Settings;
import org.hibernate.service.Service;
import org.hibernate.service.spi.Startable;
import org.hibernate.service.spi.Stoppable;
/**
* Contract for building second level cache regions.
@ -42,7 +44,7 @@
*
* @author Steve Ebersole
*/
public interface RegionFactory extends Service {
public interface RegionFactory extends Service, Startable, Stoppable {
/**
* Lifecycle callback to perform any necessary initialization of the
@ -55,16 +57,11 @@ public interface RegionFactory extends Service {
* @throws org.hibernate.cache.CacheException Indicates problems starting the L2 cache impl;
* considered as a sign to stop {@link org.hibernate.SessionFactory}
* building.
* @deprecated use {@code start} to in favor of {@link org.hibernate.service.ServiceRegistry}.
*/
@Deprecated
public void start(Settings settings, Properties properties) throws CacheException;
/**
* Lifecycle callback to perform any necessary cleanup of the underlying
* cache implementation(s). Called exactly once during
* {@link org.hibernate.SessionFactory#close}.
*/
public void stop();
/**
* By default should we perform "minimal puts" when using this second
* level cache implementation?
@ -74,6 +71,15 @@ public interface RegionFactory extends Service {
*/
public boolean isMinimalPutsEnabledByDefault();
/**
* Should we perform "minimal puts" when using this second
* level cache implementation?
*
* @return True if "minimal puts" should be performed; false
* otherwise.
*/
public boolean isMinimalPutsEnabled();
/**
* Get the default access type for {@link EntityRegion entity} and
* {@link CollectionRegion collection} regions.

View File

@ -60,7 +60,7 @@ public UpdateTimestampsCache(Settings settings, Properties props, final SessionF
String prefix = settings.getCacheRegionPrefix();
String regionName = prefix == null ? REGION_NAME : prefix + '.' + REGION_NAME;
LOG.startingUpdateTimestampsCache( regionName );
this.region = settings.getRegionFactory().buildTimestampsRegion( regionName, props );
this.region = factory.getServiceRegistry().getService( RegionFactory.class ).buildTimestampsRegion( regionName, props );
}
@SuppressWarnings({"UnusedDeclaration"})
public UpdateTimestampsCache(Settings settings, Properties props)

View File

@ -29,7 +29,6 @@
import org.hibernate.EntityMode;
import org.hibernate.MultiTenancyStrategy;
import org.hibernate.cache.spi.QueryCacheFactory;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.service.jta.platform.spi.JtaPlatform;
import org.hibernate.tuple.entity.EntityTuplizerFactory;
@ -60,15 +59,12 @@ public final class Settings {
private boolean structuredCacheEntriesEnabled;
private boolean secondLevelCacheEnabled;
private String cacheRegionPrefix;
private boolean minimalPutsEnabled;
private boolean commentsEnabled;
private boolean statisticsEnabled;
private boolean jdbcBatchVersionedData;
private boolean identifierRollbackEnabled;
private boolean flushBeforeCompletionEnabled;
private boolean autoCloseSessionEnabled;
private ConnectionReleaseMode connectionReleaseMode;
private RegionFactory regionFactory;
private QueryCacheFactory queryCacheFactory;
private QueryTranslatorFactory queryTranslatorFactory;
private boolean wrapResultSetsEnabled;
@ -136,10 +132,6 @@ public boolean isGetGeneratedKeysEnabled() {
return getGeneratedKeysEnabled;
}
public boolean isMinimalPutsEnabled() {
return minimalPutsEnabled;
}
public Integer getJdbcFetchSize() {
return jdbcFetchSize;
}
@ -168,10 +160,6 @@ public Integer getMaximumFetchDepth() {
return maximumFetchDepth;
}
public RegionFactory getRegionFactory() {
return regionFactory;
}
public boolean isQueryCacheEnabled() {
return queryCacheEnabled;
}
@ -192,10 +180,6 @@ public QueryCacheFactory getQueryCacheFactory() {
return queryCacheFactory;
}
public boolean isStatisticsEnabled() {
return statisticsEnabled;
}
public boolean isJdbcBatchVersionedData() {
return jdbcBatchVersionedData;
}
@ -260,10 +244,6 @@ public EntityTuplizerFactory getEntityTuplizerFactory() {
return entityTuplizerFactory;
}
// public ComponentTuplizerFactory getComponentTuplizerFactory() {
// return componentTuplizerFactory;
// }
// package protected setters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void setDefaultSchemaName(String string) {
@ -289,11 +269,6 @@ void setQuerySubstitutions(Map map) {
void setIdentifierRollbackEnabled(boolean b) {
identifierRollbackEnabled = b;
}
void setMinimalPutsEnabled(boolean b) {
minimalPutsEnabled = b;
}
void setScrollableResultSetsEnabled(boolean b) {
scrollableResultSetsEnabled = b;
}
@ -329,11 +304,6 @@ void setAutoUpdateSchema(boolean b) {
void setMaximumFetchDepth(Integer i) {
maximumFetchDepth = i;
}
void setRegionFactory(RegionFactory regionFactory) {
this.regionFactory = regionFactory;
}
void setQueryCacheEnabled(boolean b) {
queryCacheEnabled = b;
}
@ -354,10 +324,6 @@ void setQueryCacheFactory(QueryCacheFactory queryCacheFactory) {
this.queryCacheFactory = queryCacheFactory;
}
void setStatisticsEnabled(boolean statisticsEnabled) {
this.statisticsEnabled = statisticsEnabled;
}
void setJdbcBatchVersionedData(boolean jdbcBatchVersionedData) {
this.jdbcBatchVersionedData = jdbcBatchVersionedData;
}
@ -430,19 +396,6 @@ public void setCheckNullability(boolean checkNullability) {
this.checkNullability = checkNullability;
}
// void setComponentTuplizerFactory(ComponentTuplizerFactory componentTuplizerFactory) {
// this.componentTuplizerFactory = componentTuplizerFactory;
// }
// public BytecodeProvider getBytecodeProvider() {
// return bytecodeProvider;
// }
//
// void setBytecodeProvider(BytecodeProvider bytecodeProvider) {
// this.bytecodeProvider = bytecodeProvider;
// }
public JtaPlatform getJtaPlatform() {
return jtaPlatform;
}

View File

@ -246,18 +246,6 @@ public Settings buildSettings(Properties props, ServiceRegistry serviceRegistry)
settings.setQueryCacheFactory( createQueryCacheFactory( properties, serviceRegistry ) );
}
// The cache provider is needed when we either have second-level cache enabled
// or query cache enabled. Note that useSecondLevelCache is enabled by default
settings.setRegionFactory( serviceRegistry.getService( RegionFactory.class ) );
boolean useMinimalPuts = ConfigurationHelper.getBoolean(
Environment.USE_MINIMAL_PUTS, properties, settings.getRegionFactory().isMinimalPutsEnabledByDefault()
);
if ( debugEnabled ) {
LOG.debugf( "Optimize cache for minimal puts: %s", enabledDisabled(useMinimalPuts) );
}
settings.setMinimalPutsEnabled( useMinimalPuts );
String prefix = properties.getProperty( Environment.CACHE_REGION_PREFIX );
if ( StringHelper.isEmpty(prefix) ) {
prefix=null;
@ -273,15 +261,6 @@ public Settings buildSettings(Properties props, ServiceRegistry serviceRegistry)
}
settings.setStructuredCacheEntriesEnabled( useStructuredCacheEntries );
//Statistics and logging:
boolean useStatistics = ConfigurationHelper.getBoolean( Environment.GENERATE_STATISTICS, properties );
if ( debugEnabled ) {
LOG.debugf( "Statistics: %s", enabledDisabled(useStatistics) );
}
settings.setStatisticsEnabled( useStatistics );
boolean useIdentifierRollback = ConfigurationHelper.getBoolean( Environment.USE_IDENTIFIER_ROLLBACK, properties );
if ( debugEnabled ) {
LOG.debugf( "Deleted entity synthetic identifier rollback: %s", enabledDisabled(useIdentifierRollback) );
@ -352,7 +331,7 @@ public Settings buildSettings(Properties props, ServiceRegistry serviceRegistry)
// }
// }
private static String enabledDisabled(boolean value) {
public static String enabledDisabled(boolean value) {
return value ? "enabled" : "disabled";
}

View File

@ -33,6 +33,7 @@
import org.hibernate.LockMode;
import org.hibernate.bytecode.instrumentation.spi.LazyPropertyInitializer;
import org.hibernate.cache.spi.CacheKey;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.entry.CacheEntry;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityKey;
@ -306,7 +307,7 @@ private static void doInitializeEntity(
}
private static boolean useMinimalPuts(SessionImplementor session, EntityEntry entityEntry) {
return ( session.getFactory().getSettings().isMinimalPutsEnabled() &&
return ( session.getFactory().getServiceRegistry().getService( RegionFactory.class ).isMinimalPutsEnabled() &&
session.getCacheMode()!=CacheMode.REFRESH ) ||
( entityEntry.getPersister().hasLazyProperties() &&
entityEntry.isLoadedWithLazyPropertiesUnfetched() &&

View File

@ -37,6 +37,7 @@
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.cache.spi.CacheKey;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.entry.CollectionCacheEntry;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.CollectionEntry;
@ -335,7 +336,7 @@ private void addCollectionToCache(LoadingCollectionEntry lce, CollectionPersiste
persister.getCacheEntryStructure().structure(entry),
session.getTimestamp(),
version,
factory.getSettings().isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH
factory.getServiceRegistry().getService( RegionFactory.class ).isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH
);
if ( put && factory.getStatistics().isStatisticsEnabled() ) {

View File

@ -33,17 +33,21 @@
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.UpdateTimestampsCache;
import org.hibernate.service.Service;
import org.hibernate.service.spi.Startable;
import org.hibernate.service.spi.Stoppable;
/**
* Define internal contact of <tt>Cache API</tt>
*
* @author Strong Liu <stliu@hibernate.org>
*/
public interface CacheImplementor extends Service, Cache, Serializable {
public interface CacheImplementor extends Service, Cache,Startable, Stoppable, Serializable {
/**
* Close all cache regions.
* @deprecated use @{code Stoppable#stop}.
*/
@Deprecated
public void close();
/**

View File

@ -38,6 +38,7 @@
import org.hibernate.cache.spi.Region;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.UpdateTimestampsCache;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Settings;
import org.hibernate.engine.spi.CacheImplementor;
import org.hibernate.engine.spi.SessionFactoryImplementor;
@ -45,6 +46,10 @@
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
import org.hibernate.service.spi.InjectService;
/**
* @author Strong Liu <stliu@hibernate.org>
@ -55,36 +60,21 @@ public class CacheImpl implements CacheImplementor {
CacheImpl.class.getName()
);
private final SessionFactoryImplementor sessionFactory;
private final ServiceRegistry serviceRegistry;
private final Settings settings;
private final transient QueryCache queryCache;
private final transient RegionFactory regionFactory;
private final transient UpdateTimestampsCache updateTimestampsCache;
private final transient ConcurrentMap<String, QueryCache> queryCaches;
private final transient ConcurrentMap<String, Region> allCacheRegions = new ConcurrentHashMap<String, Region>();
private final boolean isQueryCacheEnabled;
private transient QueryCache queryCache;
private transient RegionFactory regionFactory;
private transient UpdateTimestampsCache updateTimestampsCache;
private transient ConcurrentMap<String, QueryCache> queryCaches;
private transient ConcurrentMap<String, Region> allCacheRegions = new ConcurrentHashMap<String, Region>();
public CacheImpl(SessionFactoryImplementor sessionFactory) {
this.sessionFactory = sessionFactory;
this.settings = sessionFactory.getSettings();
//todo should get this from service registry
this.regionFactory = settings.getRegionFactory();
regionFactory.start( settings, sessionFactory.getProperties() );
if ( settings.isQueryCacheEnabled() ) {
updateTimestampsCache = new UpdateTimestampsCache(
settings,
sessionFactory.getProperties(),
sessionFactory
);
queryCache = settings.getQueryCacheFactory()
.getQueryCache( null, updateTimestampsCache, settings, sessionFactory.getProperties() );
queryCaches = new ConcurrentHashMap<String, QueryCache>();
allCacheRegions.put( updateTimestampsCache.getRegion().getName(), updateTimestampsCache.getRegion() );
allCacheRegions.put( queryCache.getRegion().getName(), queryCache.getRegion() );
}
else {
updateTimestampsCache = null;
queryCache = null;
queryCaches = null;
}
this.serviceRegistry = sessionFactory.getServiceRegistry();
this.isQueryCacheEnabled = isQueryCacheEnabled();
}
@Override
@ -231,11 +221,17 @@ public boolean containsQuery(String regionName) {
@Override
public void evictDefaultQueryRegion() {
if ( sessionFactory.getSettings().isQueryCacheEnabled() ) {
if ( isQueryCacheEnabled ) {
sessionFactory.getQueryCache().clear();
}
}
private boolean isQueryCacheEnabled(){
return serviceRegistry.getService( ConfigurationService.class ).getSetting( AvailableSettings.USE_QUERY_CACHE,
StandardConverters.BOOLEAN, false
);
}
@Override
public void evictQueryRegion(String regionName) {
if ( regionName == null ) {
@ -243,7 +239,7 @@ public void evictQueryRegion(String regionName) {
"Region-name cannot be null (use Cache#evictDefaultQueryRegion to evict the default query cache)"
);
}
if ( sessionFactory.getSettings().isQueryCacheEnabled() ) {
if ( isQueryCacheEnabled ) {
QueryCache namedQueryCache = queryCaches.get( regionName );
// TODO : cleanup entries in queryCaches + allCacheRegions ?
if ( namedQueryCache != null ) {
@ -264,8 +260,8 @@ public void evictQueryRegions() {
}
@Override
public void close() {
if ( settings.isQueryCacheEnabled() ) {
public void stop() {
if ( isQueryCacheEnabled ) {
queryCache.destroy();
Iterator iter = queryCaches.values().iterator();
@ -275,8 +271,6 @@ public void close() {
}
updateTimestampsCache.destroy();
}
regionFactory.stop();
}
@Override
@ -290,7 +284,7 @@ public QueryCache getQueryCache(String regionName) throws HibernateException {
return getQueryCache();
}
if ( !settings.isQueryCacheEnabled() ) {
if ( !isQueryCacheEnabled ) {
return null;
}
@ -303,8 +297,7 @@ public QueryCache getQueryCache(String regionName) throws HibernateException {
.getQueryCache(
regionName,
updateTimestampsCache,
settings,
sessionFactory.getProperties()
sessionFactory
);
queryCaches.put( regionName, currentQueryCache );
allCacheRegions.put( currentQueryCache.getRegion().getName(), currentQueryCache.getRegion() );
@ -329,7 +322,7 @@ public UpdateTimestampsCache getUpdateTimestampsCache() {
@Override
public void evictQueries() throws HibernateException {
if ( settings.isQueryCacheEnabled() ) {
if ( isQueryCacheEnabled ) {
queryCache.clear();
}
}
@ -354,4 +347,35 @@ public Map<String, Region> getAllSecondLevelCacheRegions() {
public RegionFactory getRegionFactory() {
return regionFactory;
}
@InjectService
public void injectRegionFactory(RegionFactory regionFactory){
this.regionFactory = regionFactory;
}
@Override
public void start() {
if ( isQueryCacheEnabled ) {
updateTimestampsCache = new UpdateTimestampsCache(
settings,
sessionFactory.getProperties(),
sessionFactory
);
queryCache = settings.getQueryCacheFactory()
.getQueryCache( null, updateTimestampsCache,sessionFactory );
queryCaches = new ConcurrentHashMap<String, QueryCache>();
allCacheRegions.put( updateTimestampsCache.getRegion().getName(), updateTimestampsCache.getRegion() );
allCacheRegions.put( queryCache.getRegion().getName(), queryCache.getRegion() );
}
else {
updateTimestampsCache = null;
queryCache = null;
queryCaches = null;
}
}
@Override
public void close() {
stop();
}
}

View File

@ -770,7 +770,7 @@ public void sessionFactoryClosed(SessionFactory factory) {
.append( '.' );
}
final String cacheRegionPrefix = stringBuilder.toString();
RegionFactory regionFactory = serviceRegistry.getService( RegionFactory.class );
entityPersisters = new HashMap<String,EntityPersister>();
Map<String, RegionAccessStrategy> entityAccessStrategies = new HashMap<String, RegionAccessStrategy>();
Map<String,ClassMetadata> classMeta = new HashMap<String,ClassMetadata>();
@ -782,16 +782,18 @@ public void sessionFactoryClosed(SessionFactory factory) {
EntityRegionAccessStrategy accessStrategy = null;
if ( settings.isSecondLevelCacheEnabled() &&
rootEntityBinding.getHierarchyDetails().getCaching() != null &&
model.getHierarchyDetails().getCaching() != null &&
model.getHierarchyDetails().getCaching().getAccessType() != null ) {
model.getHierarchyDetails().getCaching() != null ) {
final String cacheRegionName = cacheRegionPrefix + rootEntityBinding.getHierarchyDetails().getCaching().getRegion();
accessStrategy = EntityRegionAccessStrategy.class.cast( entityAccessStrategies.get( cacheRegionName ) );
if ( accessStrategy == null ) {
final AccessType accessType = model.getHierarchyDetails().getCaching().getAccessType();
AccessType accessType = model.getHierarchyDetails().getCaching().getAccessType();
if ( accessType == null ) {
accessType = regionFactory.getDefaultAccessType();
}
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Building cache for entity data [{0}]", model.getEntity().getName() );
}
EntityRegion entityRegion = settings.getRegionFactory().buildEntityRegion(
EntityRegion entityRegion = serviceRegistry.getService( RegionFactory.class ).buildEntityRegion(
cacheRegionName, properties, CacheDataDescriptionImpl.decode( model )
);
accessStrategy = entityRegion.buildAccessStrategy( accessType );
@ -814,7 +816,7 @@ public void sessionFactoryClosed(SessionFactory factory) {
final CacheDataDescriptionImpl naturaIdCacheDataDescription = CacheDataDescriptionImpl.decode( model );
NaturalIdRegion naturalIdRegion = null;
try {
naturalIdRegion = settings.getRegionFactory()
naturalIdRegion = serviceRegistry.getService( RegionFactory.class )
.buildNaturalIdRegion(
naturalIdCacheRegionName,
properties,
@ -825,12 +827,12 @@ public void sessionFactoryClosed(SessionFactory factory) {
LOG.warnf(
"Shared cache region factory [%s] does not support natural id caching; " +
"shared NaturalId caching will be disabled for not be enabled for %s",
settings.getRegionFactory().getClass().getName(),
serviceRegistry.getService( RegionFactory.class ).getClass().getName(),
model.getEntity().getName()
);
}
if ( naturalIdRegion != null ) {
naturalIdAccessStrategy = naturalIdRegion.buildAccessStrategy( settings.getRegionFactory().getDefaultAccessType() );
naturalIdAccessStrategy = naturalIdRegion.buildAccessStrategy( serviceRegistry.getService( RegionFactory.class ).getDefaultAccessType() );
entityAccessStrategies.put( naturalIdCacheRegionName, naturalIdAccessStrategy );
cacheAccess.addCacheRegion( naturalIdCacheRegionName, naturalIdRegion );
}
@ -859,22 +861,24 @@ public void sessionFactoryClosed(SessionFactory factory) {
}
CollectionRegionAccessStrategy accessStrategy = null;
if ( settings.isSecondLevelCacheEnabled() &&
model.getCaching() != null &&
model.getCaching().getAccessType() != null ) {
model.getCaching() != null ) {
final String cacheRegionName = cacheRegionPrefix + model.getCaching().getRegion();
final AccessType accessType = model.getCaching().getAccessType();
AccessType accessType = model.getCaching().getAccessType();
if(accessType == null){
accessType = regionFactory.getDefaultAccessType();
}
if ( accessType != null && settings.isSecondLevelCacheEnabled() ) {
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Building cache for collection data [{0}]", model.getAttribute().getRole() );
}
CollectionRegion collectionRegion = settings.getRegionFactory().buildCollectionRegion(
CollectionRegion collectionRegion = serviceRegistry.getService( RegionFactory.class ).buildCollectionRegion(
cacheRegionName, properties, CacheDataDescriptionImpl.decode( model )
);
accessStrategy = collectionRegion.buildAccessStrategy( accessType );
entityAccessStrategies.put( cacheRegionName, accessStrategy );
cacheAccess.addCacheRegion( cacheRegionName, collectionRegion );
}
CollectionRegion collectionRegion = settings.getRegionFactory().buildCollectionRegion(
CollectionRegion collectionRegion = serviceRegistry.getService( RegionFactory.class ).buildCollectionRegion(
cacheRegionName, properties, CacheDataDescriptionImpl.decode( model )
);
accessStrategy = collectionRegion.buildAccessStrategy( accessType );
@ -1479,7 +1483,7 @@ public void close() throws HibernateException {
}
}
cacheAccess.close();
// cacheAccess.stop();
queryPlanCache.cleanup();
@ -1703,7 +1707,7 @@ public Session openSession() {
sessionOwner,
getTransactionCoordinator(),
autoJoinTransactions,
sessionFactory.settings.getRegionFactory().nextTimestamp(),
sessionFactory.getServiceRegistry().getService( RegionFactory.class ).nextTimestamp(),
interceptor,
flushBeforeCompletion,
autoClose,

View File

@ -710,21 +710,9 @@ public boolean areAssociationsLazy() {
return true;
}
private final ValueHolder<AccessType> regionFactorySpecifiedDefaultAccessType = new ValueHolder<AccessType>(
new ValueHolder.DeferredInitializer<AccessType>() {
@Override
public AccessType initialize() {
final RegionFactory regionFactory = getServiceRegistry().getService( RegionFactory.class );
return regionFactory.getDefaultAccessType();
}
}
);
@Override
public AccessType getCacheAccessType() {
return options.getDefaultAccessType() != null
? options.getDefaultAccessType()
: regionFactorySpecifiedDefaultAccessType.getValue();
return options.getDefaultAccessType();
}
}
}

View File

@ -87,7 +87,6 @@ private static List<BasicServiceInitiator> buildStandardServiceInitiatorList() {
serviceInitiators.add( SessionFactoryServiceRegistryFactoryInitiator.INSTANCE );
serviceInitiators.add( RegionFactoryInitiator.INSTANCE );
return Collections.unmodifiableList( serviceInitiators );
}

View File

@ -27,6 +27,7 @@
import java.util.Collections;
import java.util.List;
import org.hibernate.cache.internal.RegionFactoryInitiator;
import org.hibernate.engine.spi.CacheInitiator;
import org.hibernate.event.service.internal.EventListenerServiceInitiator;
import org.hibernate.service.spi.SessionFactoryServiceInitiator;
@ -47,6 +48,7 @@ private static List<SessionFactoryServiceInitiator> buildStandardServiceInitiato
serviceInitiators.add( EventListenerServiceInitiator.INSTANCE );
serviceInitiators.add( StatisticsInitiator.INSTANCE );
serviceInitiators.add( CacheInitiator.INSTANCE );
serviceInitiators.add( RegionFactoryInitiator.INSTANCE );
return Collections.unmodifiableList( serviceInitiators );
}

View File

@ -26,12 +26,15 @@
import org.jboss.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.SettingsFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.metamodel.spi.source.MetadataImplementor;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.service.spi.SessionFactoryServiceInitiator;
import org.hibernate.stat.spi.StatisticsFactory;
@ -105,7 +108,9 @@ else if ( StatisticsFactory.class.isInstance( configValue ) ) {
}
StatisticsImplementor statistics = statisticsFactory.buildStatistics( sessionFactory );
final boolean enabled = sessionFactory.getSettings().isStatisticsEnabled();
final boolean enabled = registry.getService( ConfigurationService.class ).getSetting( AvailableSettings.GENERATE_STATISTICS,
StandardConverters.BOOLEAN, false
);
statistics.setStatisticsEnabled( enabled );
LOG.debugf( "Statistics initialized [enabled=%s]", enabled );
return statistics;

View File

@ -56,6 +56,11 @@ public void configure(Configuration cfg) {
cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
}
@Override
protected void cleanupTest() throws Exception {
sessionFactory().getStatistics().clear();
}
@Test
@FailureExpectedWithNewMetamodel
public void testNaturalIdChangedWhileAttached() {

View File

@ -42,6 +42,7 @@
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactoryImpl;
import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
import org.hibernate.cache.ehcache.management.impl.ProviderMBeanRegistrationHelper;
import org.hibernate.cache.spi.AbstractRegionFactory;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.CollectionRegion;
import org.hibernate.cache.spi.EntityRegion;
@ -51,8 +52,11 @@
import org.hibernate.cache.spi.TimestampsRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Settings;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.spi.InjectService;
import org.hibernate.service.spi.ServiceRegistryAwareService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
* Abstract implementation of an Ehcache specific RegionFactory.
@ -63,7 +67,7 @@
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
abstract class AbstractEhcacheRegionFactory implements RegionFactory {
abstract class AbstractEhcacheRegionFactory extends AbstractRegionFactory {
/**
* The Hibernate system property specifying the location of the ehcache configuration file name.
@ -129,13 +133,13 @@ public long nextTimestamp() {
*/
public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), isMinimalPutsEnabled(), metadata, properties );
}
@Override
public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheNaturalIdRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
return new EhcacheNaturalIdRegion( accessStrategyFactory, getCache( regionName ), isMinimalPutsEnabled(), metadata, properties );
}
/**
@ -146,7 +150,7 @@ public CollectionRegion buildCollectionRegion(String regionName, Properties prop
return new EhcacheCollectionRegion(
accessStrategyFactory,
getCache( regionName ),
settings,
isMinimalPutsEnabled(),
metadata,
properties
);
@ -158,14 +162,6 @@ public CollectionRegion buildCollectionRegion(String regionName, Properties prop
public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties );
}
@InjectService
public void setClassLoaderService(ClassLoaderService classLoaderService) {
this.classLoaderService = classLoaderService;
}
private ClassLoaderService classLoaderService;
/**
* {@inheritDoc}
*/
@ -195,10 +191,7 @@ private Ehcache getCache(String name) throws CacheException {
* Load a resource from the classpath.
*/
protected URL loadResource(String configurationResourceName) {
URL url = null;
if ( classLoaderService != null ) {
url = classLoaderService.locateResource( configurationResourceName );
}
URL url = getServiceRegistry().getService( ClassLoaderService.class ).locateResource( configurationResourceName );
if ( url == null ) {
ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
if ( standardClassloader != null ) {
@ -222,7 +215,7 @@ protected URL loadResource(String configurationResourceName) {
return url;
}
/**
/**
* Default access-type used when the configured using JPA 2.0 config. JPA 2.0 allows <code>@Cacheable(true)</code> to be attached to an
* entity without any access type or usage qualification.
* <p/>

View File

@ -35,6 +35,8 @@
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
import org.hibernate.cfg.Settings;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
/**
* A non-singleton EhCacheRegionFactory implementation.
@ -52,65 +54,53 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
EhCacheRegionFactory.class.getName()
);
@Override
public void start() {
if ( manager != null ) {
LOG.attemptToRestartAlreadyStartedEhCacheProvider();
return;
}
public EhCacheRegionFactory() {
}
/**
* Creates a non-singleton EhCacheRegionFactory
*/
public EhCacheRegionFactory(Properties prop) {
super();
}
/**
* {@inheritDoc}
*/
public void start(Settings settings, Properties properties) throws CacheException {
this.settings = settings;
if ( manager != null ) {
LOG.attemptToRestartAlreadyStartedEhCacheProvider();
return;
}
try {
String configurationResourceName = null;
if ( properties != null ) {
configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
}
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
Configuration configuration = ConfigurationFactory.parseConfiguration();
manager = new CacheManager( configuration );
}
else {
URL url;
try {
url = new URL( configurationResourceName );
}
catch ( MalformedURLException e ) {
url = loadResource( configurationResourceName );
}
Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
manager = new CacheManager( configuration );
}
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch ( net.sf.ehcache.CacheException e ) {
if ( e.getMessage().startsWith(
"Cannot parseConfiguration CacheManager. Attempt to create a new instance of " +
"CacheManager using the diskStorePath"
) ) {
throw new CacheException(
"Attempt to restart an already started EhCacheRegionFactory. " +
"Use sessionFactory.close() between repeated calls to buildSessionFactory. " +
"Consider using SingletonEhCacheRegionFactory. Error from ehcache was: " + e.getMessage()
);
}
else {
throw new CacheException( e );
}
}
}
try {
ConfigurationService configurationService = getServiceRegistry().getService( ConfigurationService.class );
String configurationResourceName = configurationService.getSetting( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME,
StandardConverters.STRING, null
);
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
Configuration configuration = ConfigurationFactory.parseConfiguration();
manager = new CacheManager( configuration );
}
else {
URL url;
try {
url = new URL( configurationResourceName );
}
catch ( MalformedURLException e ) {
url = loadResource( configurationResourceName );
}
Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
manager = new CacheManager( configuration );
}
Properties properties = new Properties( );
properties.putAll( configurationService.getSettings() );
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch ( net.sf.ehcache.CacheException e ) {
if ( e.getMessage().startsWith(
"Cannot parseConfiguration CacheManager. Attempt to create a new instance of " +
"CacheManager using the diskStorePath"
) ) {
throw new CacheException(
"Attempt to restart an already started EhCacheRegionFactory. " +
"Use sessionFactory.close() between repeated calls to buildSessionFactory. " +
"Consider using SingletonEhCacheRegionFactory. Error from ehcache was: " + e.getMessage()
);
}
else {
throw new CacheException( e );
}
}
}
/**
* {@inheritDoc}

View File

@ -35,6 +35,8 @@
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
import org.hibernate.cfg.Settings;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
/**
* A singleton EhCacheRegionFactory implementation.
@ -52,56 +54,49 @@ public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory
);
private static final AtomicInteger REFERENCE_COUNT = new AtomicInteger();
/**
* Returns a representation of the singleton EhCacheRegionFactory
*/
public SingletonEhCacheRegionFactory(Properties prop) {
super();
}
/**
* {@inheritDoc}
*/
public void start(Settings settings, Properties properties) throws CacheException {
this.settings = settings;
try {
String configurationResourceName = null;
if ( properties != null ) {
configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
}
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
manager = CacheManager.create();
REFERENCE_COUNT.incrementAndGet();
}
else {
URL url;
try {
url = new URL( configurationResourceName );
}
catch ( MalformedURLException e ) {
if ( !configurationResourceName.startsWith( "/" ) ) {
configurationResourceName = "/" + configurationResourceName;
LOG.debugf(
"prepending / to %s. It should be placed in the root of the classpath rather than in a package.",
configurationResourceName
);
}
url = loadResource( configurationResourceName );
}
Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
manager = CacheManager.create( configuration );
REFERENCE_COUNT.incrementAndGet();
}
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch ( net.sf.ehcache.CacheException e ) {
throw new CacheException( e );
}
}
@Override
public void start() {
try {
ConfigurationService configurationService = getServiceRegistry().getService( ConfigurationService.class );
String configurationResourceName = configurationService.getSetting( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME,
StandardConverters.STRING, null
);
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
manager = CacheManager.create();
REFERENCE_COUNT.incrementAndGet();
}
else {
URL url;
try {
url = new URL( configurationResourceName );
}
catch ( MalformedURLException e ) {
if ( !configurationResourceName.startsWith( "/" ) ) {
configurationResourceName = "/" + configurationResourceName;
LOG.debugf(
"prepending / to %s. It should be placed in the root of the classpath rather than in a package.",
configurationResourceName
);
}
url = loadResource( configurationResourceName );
}
Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
manager = CacheManager.create( configuration );
REFERENCE_COUNT.incrementAndGet();
}
Properties properties = new Properties( );
properties.putAll( configurationService.getSettings() );
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch ( net.sf.ehcache.CacheException e ) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public void stop() {
try {
if ( manager != null ) {

View File

@ -54,9 +54,9 @@ public class EhcacheCollectionRegion extends EhcacheTransactionalDataRegion impl
*
* @param accessStrategyFactory
*/
public EhcacheCollectionRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
public EhcacheCollectionRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, boolean isMinimalPutsEnabled,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
super( accessStrategyFactory, underlyingCache, isMinimalPutsEnabled, metadata, properties );
}
/**

View File

@ -53,9 +53,9 @@ public class EhcacheEntityRegion extends EhcacheTransactionalDataRegion implemen
*
* @param accessStrategyFactory
*/
public EhcacheEntityRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
public EhcacheEntityRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, boolean isMinimalPutsEnabled,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
super( accessStrategyFactory, underlyingCache, isMinimalPutsEnabled, metadata, properties );
}
/**

View File

@ -54,9 +54,9 @@ public class EhcacheNaturalIdRegion extends EhcacheTransactionalDataRegion imple
*
* @param accessStrategyFactory
*/
public EhcacheNaturalIdRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
public EhcacheNaturalIdRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, boolean isMinimalPutsEnabled,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
super( accessStrategyFactory, underlyingCache, isMinimalPutsEnabled, metadata, properties );
}
@Override

View File

@ -54,10 +54,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
private static final int LOCAL_LOCK_PROVIDER_CONCURRENCY = 128;
/**
* Hibernate settings associated with the persistence unit.
*/
protected final Settings settings;
protected final boolean isMinimalPutsEnabled;
/**
* Metadata associated with the objects stored in the region.
@ -69,10 +66,10 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Construct an transactional Hibernate cache region around the given Ehcache instance.
*/
EhcacheTransactionalDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Settings settings,
EhcacheTransactionalDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, boolean isMinimalPutsEnabled,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, cache, properties );
this.settings = settings;
this.isMinimalPutsEnabled = isMinimalPutsEnabled;
this.metadata = metadata;
Object context = cache.getInternalContext();
@ -84,13 +81,8 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
}
}
/**
* Return the hibernate settings
*
* @return settings
*/
public Settings getSettings() {
return settings;
public boolean isMinimalPutsEnabled(){
return isMinimalPutsEnabled;
}
/**

View File

@ -42,17 +42,12 @@ abstract class AbstractEhcacheAccessStrategy<T extends EhcacheTransactionalDataR
* The wrapped Hibernate cache region.
*/
protected final T region;
/**
* The settings for this persistence unit.
*/
protected final Settings settings;
/**
* Create an access strategy wrapping the given region.
*/
AbstractEhcacheAccessStrategy(T region, Settings settings) {
AbstractEhcacheAccessStrategy(T region) {
this.region = region;
this.settings = settings;
}
/**
@ -63,7 +58,7 @@ abstract class AbstractEhcacheAccessStrategy<T extends EhcacheTransactionalDataR
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
*/
public final boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
return putFromLoad( key, value, txTimestamp, version, settings.isMinimalPutsEnabled() );
return putFromLoad( key, value, txTimestamp, version, region.isMinimalPutsEnabled() );
}
/**

View File

@ -59,8 +59,8 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
/**
* Creates a read/write cache access strategy around the given cache region.
*/
public AbstractReadWriteEhcacheAccessStrategy(T region, Settings settings) {
super( region, settings );
public AbstractReadWriteEhcacheAccessStrategy(T region) {
super( region );
this.versionComparator = region.getCacheDataDescription().getVersionComparator();
}

View File

@ -56,21 +56,19 @@ public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntity
if ( entityRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( entityRegion.getName() );
}
return new ReadOnlyEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
return new ReadOnlyEhcacheEntityRegionAccessStrategy( entityRegion );
case READ_WRITE:
return new ReadWriteEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
return new ReadWriteEhcacheEntityRegionAccessStrategy( entityRegion );
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheEntityRegionAccessStrategy(
entityRegion,
entityRegion.getSettings()
entityRegion
);
case TRANSACTIONAL:
return new TransactionalEhcacheEntityRegionAccessStrategy(
entityRegion,
entityRegion.getEhcache(),
entityRegion.getSettings()
entityRegion.getEhcache()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
@ -90,23 +88,19 @@ public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(Ehcac
LOG.readOnlyCacheConfiguredForMutableEntity( collectionRegion.getName() );
}
return new ReadOnlyEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
collectionRegion
);
case READ_WRITE:
return new ReadWriteEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
collectionRegion
);
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
collectionRegion
);
case TRANSACTIONAL:
return new TransactionalEhcacheCollectionRegionAccessStrategy(
collectionRegion, collectionRegion.getEhcache(), collectionRegion
.getSettings()
collectionRegion, collectionRegion.getEhcache()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
@ -122,23 +116,19 @@ public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(Ehcache
LOG.readOnlyCacheConfiguredForMutableEntity( naturalIdRegion.getName() );
}
return new ReadOnlyEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
naturalIdRegion
);
case READ_WRITE:
return new ReadWriteEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
naturalIdRegion
);
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
naturalIdRegion
);
case TRANSACTIONAL:
return new TransactionalEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion, naturalIdRegion.getEhcache(), naturalIdRegion
.getSettings()
naturalIdRegion, naturalIdRegion.getEhcache()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );

View File

@ -43,8 +43,8 @@ public class NonStrictReadWriteEhcacheCollectionRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given collection region.
*/
public NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) {
super( region, settings );
public NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region) {
super( region );
}
/**

View File

@ -43,8 +43,8 @@ public class NonStrictReadWriteEhcacheEntityRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given collection region.
*/
public NonStrictReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) {
super( region, settings );
public NonStrictReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region) {
super( region );
}
/**

View File

@ -43,8 +43,8 @@ public class NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given NaturalId region.
*/
public NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) {
super( region, settings );
public NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region) {
super( region );
}
/**

View File

@ -43,8 +43,8 @@ public class ReadOnlyEhcacheCollectionRegionAccessStrategy
/**
* Create a read-only access strategy accessing the given collection region.
*/
public ReadOnlyEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) {
super( region, settings );
public ReadOnlyEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region) {
super( region );
}
/**

View File

@ -46,8 +46,8 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
/**
* Create a read-only access strategy accessing the given entity region.
*/
public ReadOnlyEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) {
super( region, settings );
public ReadOnlyEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region) {
super( region );
}
/**

View File

@ -43,8 +43,8 @@ public class ReadOnlyEhcacheNaturalIdRegionAccessStrategy
/**
* Create a read-only access strategy accessing the given NaturalId region.
*/
public ReadOnlyEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) {
super( region, settings );
public ReadOnlyEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region) {
super( region );
}
/**

View File

@ -41,8 +41,8 @@ public class ReadWriteEhcacheCollectionRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given collection region.
*/
public ReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) {
super( region, settings );
public ReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region) {
super( region );
}
/**

View File

@ -43,8 +43,8 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given entity region.
*/
public ReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) {
super( region, settings );
public ReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region) {
super( region );
}
/**

View File

@ -43,8 +43,8 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given NaturalId region.
*/
public ReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) {
super( region, settings );
public ReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region) {
super( region );
}
/**

View File

@ -51,10 +51,9 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
*
* @param region the Hibernate region.
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
public TransactionalEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Ehcache ehcache, Settings settings) {
super( region, settings );
public TransactionalEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Ehcache ehcache) {
super( region );
this.ehcache = ehcache;
}

View File

@ -50,10 +50,9 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
*
* @param region the Hibernate region.
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
public TransactionalEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Ehcache ehcache, Settings settings) {
super( region, settings );
public TransactionalEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Ehcache ehcache) {
super( region );
this.ehcache = ehcache;
}

View File

@ -51,10 +51,9 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
*
* @param region the Hibernate region.
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
public TransactionalEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Ehcache ehcache, Settings settings) {
super( region, settings );
public TransactionalEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Ehcache ehcache) {
super( region );
this.ehcache = ehcache;
}

View File

@ -13,8 +13,8 @@ public class ItemValueExtractor extends AbstractReadWriteEhcacheAccessStrategy {
/**
* Creates a read/write cache access strategy around the given cache region.
*/
public ItemValueExtractor(EhcacheTransactionalDataRegion region, Settings settings) {
super(region, settings);
public ItemValueExtractor(EhcacheTransactionalDataRegion region) {
super(region);
}

View File

@ -310,7 +310,7 @@ public void evictAll() {
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> cls) {
if ( RegionFactory.class.isAssignableFrom( cls ) ) {
return (T) sessionFactory.getSettings().getRegionFactory();
return (T) sessionFactory.getServiceRegistry().getService( RegionFactory.class );
}
if ( org.hibernate.Cache.class.isAssignableFrom( cls ) ) {
return (T) sessionFactory.getCache();

View File

@ -148,9 +148,6 @@ private Configuration buildConfiguration(SharedCacheMode mode) {
}
public static class CustomRegionFactory extends NoCachingRegionFactory {
public CustomRegionFactory() {
}
@Override
public AccessType getDefaultAccessType() {
return AccessType.READ_WRITE;

View File

@ -3,7 +3,6 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@ -25,6 +24,7 @@
import org.hibernate.cache.infinispan.impl.BaseRegion;
import org.hibernate.cache.infinispan.naturalid.NaturalIdRegionImpl;
import org.hibernate.cache.infinispan.util.CacheCommandFactory;
import org.hibernate.cache.spi.AbstractRegionFactory;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.infinispan.collection.CollectionRegionImpl;
@ -45,10 +45,9 @@
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Settings;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
import org.hibernate.service.spi.ServiceRegistryAwareService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
* A {@link RegionFactory} for <a href="http://www.jboss.org/infinispan">Infinispan</a>-backed cache
@ -58,7 +57,7 @@
* @author Galder Zamarreño
* @since 3.5
*/
public class InfinispanRegionFactory implements RegionFactory, ServiceRegistryAwareService {
public class InfinispanRegionFactory extends AbstractRegionFactory {
private static final Log log = LogFactory.getLog(InfinispanRegionFactory.class);
@ -172,8 +171,6 @@ public class InfinispanRegionFactory implements RegionFactory, ServiceRegistryAw
private EmbeddedCacheManager manager;
protected ServiceRegistryImplementor serviceRegistry;
private final Map<String, TypeOverrides> typeOverrides = new HashMap<String, TypeOverrides>();
private final Set<String> definedConfigurations = new HashSet<String>();
@ -184,21 +181,6 @@ public class InfinispanRegionFactory implements RegionFactory, ServiceRegistryAw
private List<String> regionNames = new ArrayList<String>();
/**
* Create a new instance using the default configuration.
*/
public InfinispanRegionFactory() {
}
/**
* Create a new instance using conifguration properties in <code>props</code>.
*
* @param props
* Environmental properties; currently unused.
*/
public InfinispanRegionFactory(Properties props) {
}
/** {@inheritDoc} */
public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException {
if (log.isDebugEnabled()) log.debug("Building collection cache region [" + regionName + "]");
@ -300,44 +282,44 @@ public EmbeddedCacheManager getCacheManager() {
return manager;
}
/**
@Override
public void start() {
log.debug("Starting Infinispan region factory");
try {
transactionManagerlookup = createTransactionManagerLookup( getServiceRegistry() );
transactionManager = transactionManagerlookup.getTransactionManager();
manager = createCacheManager();
initGenericDataTypeOverrides();
ConfigurationService configurationService = getServiceRegistry().getService( ConfigurationService.class );
Map settings = configurationService.getSettings();
for(Object key : settings.keySet()){
int prefixLoc;
if ((prefixLoc = key.toString().indexOf( PREFIX )) != -1) {
dissectProperty(prefixLoc, key.toString(), settings);
}
}
defineGenericDataTypeCacheConfigurations( settings);
} catch (CacheException ce) {
throw ce;
} catch (Throwable t) {
throw new CacheException("Unable to start region factory", t);
}
}
/**
* {@inheritDoc}
*/
@Override
public void start(Settings settings, Properties properties) throws CacheException {
log.debug("Starting Infinispan region factory");
try {
transactionManagerlookup = createTransactionManagerLookup(settings, properties);
transactionManager = transactionManagerlookup.getTransactionManager();
manager = createCacheManager();
initGenericDataTypeOverrides();
Enumeration keys = properties.propertyNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
int prefixLoc;
if ((prefixLoc = key.indexOf(PREFIX)) != -1) {
dissectProperty(prefixLoc, key, properties);
}
}
defineGenericDataTypeCacheConfigurations(settings, properties);
} catch (CacheException ce) {
throw ce;
} catch (Throwable t) {
throw new CacheException("Unable to start region factory", t);
}
start();
}
protected org.infinispan.transaction.lookup.TransactionManagerLookup createTransactionManagerLookup(
Settings settings, Properties properties) {
return new HibernateTransactionManagerLookup(settings, properties);
ServiceRegistry sr) {
return new HibernateTransactionManagerLookup(sr);
}
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
/**
* {@inheritDoc}
*/
@ -375,7 +357,7 @@ public Set<String> getDefinedConfigurations() {
protected EmbeddedCacheManager createCacheManager() throws CacheException {
try {
ConfigurationService configurationService = serviceRegistry.getService( ConfigurationService.class );
ConfigurationService configurationService = getServiceRegistry().getService( ConfigurationService.class );
String configLoc = configurationService.getSetting(
INFINISPAN_CONFIG_RESOURCE_PROP,
StandardConverters.STRING, DEF_INFINISPAN_CONFIG_RESOURCE
@ -403,7 +385,7 @@ private void startRegion(BaseRegion region, String regionName) {
.addRegion(regionName, region);
}
private Map<String, TypeOverrides> initGenericDataTypeOverrides() {
public void initGenericDataTypeOverrides() {
TypeOverrides entityOverrides = new TypeOverrides();
entityOverrides.setCacheName(DEF_ENTITY_RESOURCE);
typeOverrides.put(ENTITY_KEY, entityOverrides);
@ -419,10 +401,9 @@ private Map<String, TypeOverrides> initGenericDataTypeOverrides() {
TypeOverrides queryOverrides = new TypeOverrides();
queryOverrides.setCacheName(DEF_QUERY_RESOURCE);
typeOverrides.put(QUERY_KEY, queryOverrides);
return typeOverrides;
}
private void dissectProperty(int prefixLoc, String key, Properties properties) {
private void dissectProperty(int prefixLoc, String key, Map properties) {
TypeOverrides cfgOverride;
int suffixLoc;
if (!key.equals(INFINISPAN_CONFIG_RESOURCE_PROP) && (suffixLoc = key.indexOf(CONFIG_SUFFIX)) != -1) {
@ -446,8 +427,8 @@ private void dissectProperty(int prefixLoc, String key, Properties properties) {
}
}
private String extractProperty(String key, Properties properties) {
String value = ConfigurationHelper.extractPropertyValue(key, properties);
private String extractProperty(String key, Map properties) {
String value = ConfigurationHelper.getString( key, properties );
log.debugf("Configuration override via property %s: %s", key, value);
return value;
}
@ -462,7 +443,7 @@ private TypeOverrides getOrCreateConfig(int prefixLoc, String key, int suffixLoc
return cfgOverride;
}
private void defineGenericDataTypeCacheConfigurations(Settings settings, Properties properties) throws CacheException {
private void defineGenericDataTypeCacheConfigurations(Map properties) throws CacheException {
String[] defaultGenericDataTypes = new String[]{ENTITY_KEY, COLLECTION_KEY, TIMESTAMPS_KEY, QUERY_KEY};
for (String type : defaultGenericDataTypes) {
TypeOverrides override = overrideStatisticsIfPresent(typeOverrides.get(type), properties);
@ -529,7 +510,7 @@ protected AdvancedCache createCacheWrapper(AdvancedCache cache) {
return new ClassLoaderAwareCache(cache, Thread.currentThread().getContextClassLoader());
}
private Configuration configureTransactionManager(Configuration regionOverrides, String templateCacheName, Properties properties) {
private Configuration configureTransactionManager(Configuration regionOverrides, String templateCacheName, Map properties) {
// Get existing configuration to verify whether a tm was configured or not.
Configuration templateConfig = manager.defineConfiguration(templateCacheName, new Configuration());
if (templateConfig.isTransactionalCache()) {
@ -539,7 +520,7 @@ private Configuration configureTransactionManager(Configuration regionOverrides,
log.debug("Infinispan is configured [" + ispnTmLookupClassName + "] with a different transaction manager lookup " +
"class than Hibernate [" + hbTmLookupClassName + "]");
} else {
regionOverrides.setTransactionManagerLookup(transactionManagerlookup);
regionOverrides.fluent().transactionManagerLookup( transactionManagerlookup );
}
String useSyncProp = extractProperty(INFINISPAN_USE_SYNCHRONIZATION_PROP, properties);
@ -550,11 +531,12 @@ private Configuration configureTransactionManager(Configuration regionOverrides,
return regionOverrides;
}
private TypeOverrides overrideStatisticsIfPresent(TypeOverrides override, Properties properties) {
private TypeOverrides overrideStatisticsIfPresent(TypeOverrides override, Map properties) {
String globalStats = extractProperty(INFINISPAN_GLOBAL_STATISTICS_PROP, properties);
if (globalStats != null) {
override.setExposeStatistics(Boolean.parseBoolean(globalStats));
}
return override;
}
}

View File

@ -52,25 +52,16 @@ public class JndiInfinispanRegionFactory extends InfinispanRegionFactory {
* There is no default value -- the user must specify the property.
*/
public static final String CACHE_MANAGER_RESOURCE_PROP = "hibernate.cache.infinispan.cachemanager";
public JndiInfinispanRegionFactory() {
super();
}
public JndiInfinispanRegionFactory(Properties props) {
super(props);
}
@Override
protected EmbeddedCacheManager createCacheManager() throws CacheException {
String name = serviceRegistry.getService( ConfigurationService.class ).getSetting(
String name = getServiceRegistry().getService( ConfigurationService.class ).getSetting(
CACHE_MANAGER_RESOURCE_PROP,
StandardConverters.STRING
);
if ( name == null ) {
throw new CacheException( "Configuration property " + CACHE_MANAGER_RESOURCE_PROP + " not set" );
}
JndiService jndiService = serviceRegistry.getService( JndiService.class );
JndiService jndiService = getServiceRegistry().getService( JndiService.class );
return (EmbeddedCacheManager) jndiService.locate( name );
}

View File

@ -25,6 +25,7 @@
import javax.transaction.TransactionManager;
import org.hibernate.cfg.Settings;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.jta.platform.spi.JtaPlatform;
/**
@ -45,6 +46,15 @@ public HibernateTransactionManagerLookup(Settings settings, Properties propertie
}
}
public HibernateTransactionManagerLookup(ServiceRegistry serviceRegistry) {
if ( serviceRegistry != null ) {
jtaPlatform = serviceRegistry.getService( JtaPlatform.class );
}
else {
jtaPlatform = null;
}
}
public TransactionManager getTransactionManager() throws Exception {
return jtaPlatform == null ? null : jtaPlatform.retrieveTransactionManager();
}

View File

@ -77,21 +77,6 @@ public void releaseCachSupport() throws Exception {
System.setProperty(JGROUPS_CFG_FILE, jgroupsCfgFile);
}
protected void registerCache(Cache cache) {
testSupport.registerCache(cache);
}
protected void unregisterCache(Cache cache) {
testSupport.unregisterCache(cache);
}
protected void registerFactory(RegionFactory factory) {
testSupport.registerFactory(factory);
}
protected void unregisterFactory(RegionFactory factory) {
testSupport.unregisterFactory(factory);
}
protected CacheTestSupport getCacheTestSupport() {
return testSupport;

View File

@ -32,7 +32,9 @@
import org.hibernate.cache.infinispan.entity.EntityRegionImpl;
import org.hibernate.cache.infinispan.util.FlagAdapter;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.internal.StandardServiceRegistryImpl;
import org.hibernate.test.cache.infinispan.util.CacheTestUtil;
@ -49,6 +51,7 @@ public class NodeEnvironment {
private StandardServiceRegistryImpl serviceRegistry;
private InfinispanRegionFactory regionFactory;
private SessionFactoryImplementor sessionFactory;
private Map<String,EntityRegionImpl> entityRegionMap;
private Map<String,CollectionRegionImpl> collectionRegionMap;
@ -114,7 +117,8 @@ public void prepare() throws Exception {
serviceRegistry = (StandardServiceRegistryImpl) new ServiceRegistryBuilder()
.applySettings( configuration.getProperties() )
.buildServiceRegistry();
regionFactory = CacheTestUtil.startRegionFactory( serviceRegistry, configuration );
sessionFactory = (SessionFactoryImplementor)configuration.buildSessionFactory( serviceRegistry );
regionFactory = (InfinispanRegionFactory)sessionFactory.getServiceRegistry().getService( RegionFactory.class );
}
public void release() throws Exception {
@ -144,9 +148,8 @@ public Void call() throws Exception {
}
collectionRegionMap.clear();
}
if ( regionFactory != null ) {
// Currently the RegionFactory is shutdown by its registration with the CacheTestSetup from CacheTestUtil when built
regionFactory.stop();
if ( sessionFactory != null ) {
sessionFactory.close();
}
if ( serviceRegistry != null ) {
serviceRegistry.destroy();

View File

@ -131,7 +131,7 @@ public void testRedeployment() throws Exception {
rebuildSessionFactory();
addEntityCheckCache( );
JndiInfinispanRegionFactory regionFactory = (JndiInfinispanRegionFactory) sessionFactory().getSettings().getRegionFactory();
JndiInfinispanRegionFactory regionFactory = (JndiInfinispanRegionFactory) sessionFactory().getServiceRegistry().getService( RegionFactory.class );
Cache cache = regionFactory.getCacheManager().getCache( "org.hibernate.test.cache.infinispan.functional.Item" );
assertEquals( ComponentStatus.RUNNING, cache.getStatus() );
}

View File

@ -30,6 +30,7 @@
import org.hibernate.cache.CacheException;
import org.hibernate.cache.infinispan.InfinispanRegionFactory;
import org.hibernate.cache.spi.AbstractRegionFactory;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.CollectionRegion;
import org.hibernate.cache.spi.EntityRegion;
@ -39,6 +40,11 @@
import org.hibernate.cache.spi.TimestampsRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Settings;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
import org.hibernate.service.spi.InjectService;
import org.hibernate.service.spi.ServiceRegistryAwareService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
* ClusterAwareRegionFactory.
@ -46,7 +52,7 @@
* @author Galder Zamarreño
* @since 3.5
*/
public class ClusterAwareRegionFactory implements RegionFactory {
public class ClusterAwareRegionFactory extends AbstractRegionFactory {
private static final Log log = LogFactory.getLog(ClusterAwareRegionFactory.class);
private static final Hashtable<String, EmbeddedCacheManager> cacheManagers = new Hashtable<String, EmbeddedCacheManager>();
@ -54,10 +60,7 @@ public class ClusterAwareRegionFactory implements RegionFactory {
private final InfinispanRegionFactory delegate = new InfinispanRegionFactory();
private String cacheManagerName;
private boolean locallyAdded;
public ClusterAwareRegionFactory(Properties props) {
}
public static EmbeddedCacheManager getCacheManager(String name) {
return cacheManagers.get(name);
}
@ -77,18 +80,35 @@ public static void clearCacheManagers() {
cacheManagers.clear();
}
public void start(Settings settings, Properties properties) throws CacheException {
cacheManagerName = properties.getProperty(DualNodeTestCase.NODE_ID_PROP);
EmbeddedCacheManager existing = getCacheManager(cacheManagerName);
locallyAdded = (existing == null);
if (locallyAdded) {
delegate.start(settings, properties);
cacheManagers.put(cacheManagerName, delegate.getCacheManager());
} else {
delegate.setCacheManager(existing);
}
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
super.injectServices( serviceRegistry );
delegate.injectServices( serviceRegistry );
}
@InjectService
public void setConfigurationService(ConfigurationService configurationService){
cacheManagerName = configurationService.getSetting( DualNodeTestCase.NODE_ID_PROP, StandardConverters.STRING );
}
@Override
public void start() {
EmbeddedCacheManager existing = getCacheManager(cacheManagerName);
locallyAdded = (existing == null);
if (locallyAdded) {
delegate.start();
cacheManagers.put(cacheManagerName, delegate.getCacheManager());
} else {
delegate.initGenericDataTypeOverrides();
delegate.setCacheManager(existing);
}
}
public void start(Settings settings, Properties properties) throws CacheException {
start();
}
public void stop() {

View File

@ -259,18 +259,6 @@ public void nodeVisited(CacheEntryVisitedEvent event) {
if ( !event.isPre() ) {
NaturalIdCacheKey cacheKey = (NaturalIdCacheKey) event.getKey();
visited.add(cacheKey.toString());
// Integer primKey = (Integer) cacheKey.getKey();
// String key = (String) cacheKey.getEntityOrRoleName() + '#' + primKey;
// log.debug( "MyListener[" + name + "] - Visiting key " + key );
// // String name = fqn.toString();
// String token = ".functional.";
// int index = key.indexOf( token );
// if ( index > -1 ) {
// index += token.length();
// key = key.substring( index );
// log.debug( "MyListener[" + name + "] - recording visit to " + key );
// visited.add( key );
// }
}
}
}

View File

@ -127,18 +127,6 @@ protected Configuration createConfiguration() {
public static class MockInfinispanRegionFactory extends InfinispanRegionFactory {
public MockInfinispanRegionFactory() {
}
public MockInfinispanRegionFactory(Properties props) {
super(props);
}
// @Override
// protected TimestampsRegionImpl createTimestampsRegion(CacheAdapter cacheAdapter, String regionName) {
// return new MockTimestampsRegionImpl(cacheAdapter, regionName, getTransactionManager(), this);
// }
@Override
protected AdvancedCache createCacheWrapper(AdvancedCache cache) {
return new ClassLoaderAwareCache(cache, Thread.currentThread().getContextClassLoader()) {

View File

@ -25,8 +25,10 @@
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
@ -82,6 +84,7 @@ public class JBossStandaloneJtaExampleTest {
Main jndiServer;
private ServiceRegistry serviceRegistry;
@Before
public void setUp() throws Exception {
jndiServer = startJndiServer();
@ -206,6 +209,10 @@ public <T> T unwrap(Class<T> iface) throws SQLException {
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false; // JDK6 stuff
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
}
private Main startJndiServer() throws Exception {
@ -296,6 +303,7 @@ private SessionFactory buildSessionFactory() {
Properties envProps = Environment.getProperties();
envProps.put(AvailableSettings.JTA_PLATFORM, new JBossStandAloneJtaPlatform());
envProps.putAll( cfg.getProperties() );
serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry(envProps);
String[] mappings = new String[]{"org/hibernate/test/cache/infinispan/functional/Item.hbm.xml"};

View File

@ -23,14 +23,18 @@
*/
package org.hibernate.test.cache.infinispan.util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.infinispan.Cache;
import org.jboss.logging.Logger;
import org.hibernate.cache.infinispan.InfinispanRegionFactory;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
/**
* Support class for tracking and cleaning up objects used in tests.
@ -43,7 +47,7 @@ public class CacheTestSupport {
private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack";
private Set<Cache> caches = new HashSet();
private Set<RegionFactory> factories = new HashSet();
private Map<InfinispanRegionFactory, SessionFactoryImplementor> factories = new HashMap();
private Exception exception;
private String preferIPv4Stack;
@ -51,16 +55,16 @@ public void registerCache(Cache cache) {
caches.add(cache);
}
public void registerFactory(RegionFactory factory) {
factories.add(factory);
public void registerFactory(InfinispanRegionFactory regionFactory, SessionFactoryImplementor factory) {
factories.put( regionFactory, factory );
}
public void unregisterCache(Cache cache) {
caches.remove( cache );
}
public void unregisterFactory(RegionFactory factory) {
factories.remove( factory );
public SessionFactoryImplementor unregisterFactory(InfinispanRegionFactory regionFactory) {
return factories.remove( regionFactory );
}
public void setUp() throws Exception {
@ -100,9 +104,9 @@ private void sleep(long ms) {
}
private void cleanUp() {
for (Iterator it = factories.iterator(); it.hasNext(); ) {
for (Iterator it = factories.values().iterator(); it.hasNext(); ) {
try {
((RegionFactory) it.next()).stop();
((SessionFactoryImplementor) it.next()).close();
}
catch (Exception e) {
storeException(e);

View File

@ -32,11 +32,14 @@
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.hibernate.SessionFactory;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.infinispan.InfinispanRegionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.Settings;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.ServiceRegistry;
/**
@ -73,32 +76,21 @@ public static Configuration buildCustomQueryCacheConfiguration(String regionPref
return cfg;
}
public static InfinispanRegionFactory startRegionFactory(
ServiceRegistry serviceRegistry,
Configuration cfg) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Settings settings = cfg.buildSettings( serviceRegistry );
Properties properties = cfg.getProperties();
String factoryType = cfg.getProperty(Environment.CACHE_REGION_FACTORY);
Class factoryClass = Thread.currentThread().getContextClassLoader().loadClass(factoryType);
InfinispanRegionFactory regionFactory = (InfinispanRegionFactory) factoryClass.newInstance();
regionFactory.start(settings, properties);
return regionFactory;
}
public static InfinispanRegionFactory startRegionFactory(
ServiceRegistry serviceRegistry,
Configuration cfg,
CacheTestSupport testSupport) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
InfinispanRegionFactory factory = startRegionFactory( serviceRegistry, cfg );
testSupport.registerFactory(factory);
SessionFactoryImplementor sessionFactory =(SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry );
InfinispanRegionFactory factory = (InfinispanRegionFactory) sessionFactory.getServiceRegistry().getService( RegionFactory.class );
testSupport.registerFactory(factory, sessionFactory);
return factory;
}
public static void stopRegionFactory(InfinispanRegionFactory factory, CacheTestSupport testSupport) {
factory.stop();
testSupport.unregisterFactory(factory);
testSupport.unregisterFactory(factory).close();
}
/**

View File

@ -41,7 +41,7 @@ protected BaseGeneralDataRegion getInternalRegion() {
@Override
protected boolean isDefaultMinimalPutOverride() {
return region.getSettings().isMinimalPutsEnabled();
return region.isMinimalPutsEnabled();
}
@Override

View File

@ -79,6 +79,6 @@ protected BaseGeneralDataRegion getInternalRegion() {
@Override
protected boolean isDefaultMinimalPutOverride() {
return region.getSettings().isMinimalPutsEnabled();
return region.isMinimalPutsEnabled();
}
}

View File

@ -41,7 +41,7 @@ protected BaseGeneralDataRegion getInternalRegion() {
@Override
protected boolean isDefaultMinimalPutOverride() {
return region.getSettings().isMinimalPutsEnabled();
return region.isMinimalPutsEnabled();
}
@Override

View File

@ -28,6 +28,7 @@
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.spi.AbstractRegionFactory;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.CollectionRegion;
import org.hibernate.cache.spi.EntityRegion;
@ -36,17 +37,20 @@
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.TimestampsRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Settings;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.config.spi.StandardConverters;
import org.hibernate.service.spi.InjectService;
/**
* @author Strong Liu
*/
public class CachingRegionFactory implements RegionFactory {
public class CachingRegionFactory extends AbstractRegionFactory {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class, CachingRegionFactory.class.getName()
);
private Settings settings;
public CachingRegionFactory() {
LOG.warn( "CachingRegionFactory should be only used for testing." );
}
@ -56,9 +60,10 @@ public CachingRegionFactory(Properties properties) {
LOG.warn( "CachingRegionFactory should be only used for testing." );
}
@Override
public void start(Settings settings, Properties properties) throws CacheException {
this.settings=settings;
public void start() {
}
@Override
@ -83,19 +88,19 @@ public long nextTimestamp() {
@Override
public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EntityRegionImpl( regionName, metadata, settings );
return new EntityRegionImpl( regionName, metadata, isMinimalPutsEnabled() );
}
@Override
public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new NaturalIdRegionImpl( regionName, metadata, settings );
return new NaturalIdRegionImpl( regionName, metadata, isMinimalPutsEnabled() );
}
@Override
public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new CollectionRegionImpl( regionName, metadata, settings );
return new CollectionRegionImpl( regionName, metadata, isMinimalPutsEnabled() );
}
@Override

View File

@ -40,14 +40,14 @@ class CollectionRegionImpl extends BaseTransactionalDataRegion implements Collec
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class, CollectionRegionImpl.class.getName()
);
private final Settings settings;
CollectionRegionImpl(String name, CacheDataDescription metadata, Settings settings) {
private final boolean isMinimalPutsEnabled;
CollectionRegionImpl(String name, CacheDataDescription metadata, boolean isMinimalPutsEnabled) {
super( name, metadata );
this.settings=settings;
this.isMinimalPutsEnabled=isMinimalPutsEnabled;
}
public Settings getSettings() {
return settings;
public boolean isMinimalPutsEnabled() {
return isMinimalPutsEnabled;
}
@Override

View File

@ -40,17 +40,16 @@ class EntityRegionImpl extends BaseTransactionalDataRegion implements EntityRegi
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class, EntityRegionImpl.class.getName()
);
private final Settings settings;
private final boolean isMinimalPutsEnabled;
EntityRegionImpl(String name, CacheDataDescription metadata, Settings settings) {
EntityRegionImpl(String name, CacheDataDescription metadata, boolean isMinimalPutsEnabled) {
super( name, metadata );
this.settings = settings;
this.isMinimalPutsEnabled = isMinimalPutsEnabled;
}
public Settings getSettings() {
return settings;
public boolean isMinimalPutsEnabled() {
return isMinimalPutsEnabled;
}
@Override

View File

@ -40,14 +40,14 @@ class NaturalIdRegionImpl extends BaseTransactionalDataRegion implements Natural
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class, NaturalIdRegionImpl.class.getName()
);
private final Settings settings;
NaturalIdRegionImpl(String name, CacheDataDescription metadata, Settings settings) {
private final boolean isMinimalPutsEnabled;
NaturalIdRegionImpl(String name, CacheDataDescription metadata, boolean isMinimalPutsEnabled) {
super( name, metadata );
this.settings=settings;
this.isMinimalPutsEnabled=isMinimalPutsEnabled;
}
public Settings getSettings() {
return settings;
public boolean isMinimalPutsEnabled() {
return isMinimalPutsEnabled;
}
@Override

View File

@ -52,7 +52,7 @@ protected BaseGeneralDataRegion getInternalRegion() {
@Override
protected boolean isDefaultMinimalPutOverride() {
return region.getSettings().isMinimalPutsEnabled();
return region.isMinimalPutsEnabled();
}
@Override

View File

@ -108,7 +108,7 @@ protected BaseGeneralDataRegion getInternalRegion() {
@Override
protected boolean isDefaultMinimalPutOverride() {
return region.getSettings().isMinimalPutsEnabled();
return region.isMinimalPutsEnabled();
}
@Override

View File

@ -111,7 +111,7 @@ protected BaseGeneralDataRegion getInternalRegion() {
@Override
protected boolean isDefaultMinimalPutOverride() {
return region.getSettings().isMinimalPutsEnabled();
return region.isMinimalPutsEnabled();
}
@Override

View File

@ -159,6 +159,14 @@ public Boolean convert(Object value) {
afterSessionFactoryBuilt();
}
protected void rebuildSessionFactory() {
if ( sessionFactory == null ) {
return;
}
buildSessionFactory();
}
protected void afterConstructAndConfigureMetadata(MetadataImplementor metadataImplementor) {
}
@ -440,28 +448,6 @@ public void onFailure() {
}
}
protected void rebuildSessionFactory() {
if ( sessionFactory == null ) {
return;
}
sessionFactory.close();
serviceRegistry.destroy();
serviceRegistry = buildServiceRegistry( configuration );
if ( isMetadataUsed ) {
// need to rebuild metadata because serviceRegistry was recreated
MetadataImplementor metadataImplementor = buildMetadata( serviceRegistry );
afterConstructAndConfigureMetadata( metadataImplementor );
applyCacheSettings(metadataImplementor);
sessionFactory = ( SessionFactoryImplementor ) metadataImplementor.buildSessionFactory();
}
else {
sessionFactory = ( SessionFactoryImplementor ) configuration.buildSessionFactory( serviceRegistry );
}
afterSessionFactoryBuilt();
}
// before/after each test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Before