@Override public void write(ObjectDataOutput out, CacheKey object) throws IOException { try { Object key = UNSAFE.getObject(object, KEY_OFFSET); Type type = (Type) UNSAFE.getObject(object, TYPE_OFFSET); String entityOrRoleName = (String) UNSAFE.getObject(object, ENTITY_OR_ROLE_NAME_OFFSET); EntityMode entityMode = (EntityMode) UNSAFE.getObject(object, ENTITY_MODE_OFFSET); int hashCode = UNSAFE.getInt(object, HASH_CODE_OFFSET); out.writeObject(key); out.writeObject(type); out.writeUTF(entityOrRoleName); out.writeUTF(entityMode.toString()); out.writeInt(hashCode); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } }
@Override public CacheKey read(ObjectDataInput in) throws IOException { try { Object key = in.readObject(); Type type = in.readObject(); String entityOrRoleName = in.readUTF(); EntityMode entityMode = EntityMode.parse(in.readUTF()); int hashCode = in.readInt(); CacheKey cacheKey = (CacheKey) UNSAFE.allocateInstance(CacheKey.class); UNSAFE.putObjectVolatile(cacheKey, KEY_OFFSET, key); UNSAFE.putObjectVolatile(cacheKey, TYPE_OFFSET, type); UNSAFE.putObjectVolatile(cacheKey, ENTITY_OR_ROLE_NAME_OFFSET, entityOrRoleName); UNSAFE.putObjectVolatile(cacheKey, ENTITY_MODE_OFFSET, entityMode); UNSAFE.putIntVolatile(cacheKey, HASH_CODE_OFFSET, hashCode); return cacheKey; } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } }
@Test public void testAutoregistrationOnHibernate3Available() throws Exception { HazelcastInstance hz = Hazelcast.newHazelcastInstance(); HazelcastInstanceImpl impl = (HazelcastInstanceImpl) ORIGINAL.get(hz); SerializationService ss = impl.getSerializationService(); ConcurrentMap<Class, ?> typeMap = (ConcurrentMap<Class, ?>) TYPE_MAP.get(ss); boolean cacheKeySerializerFound = false; boolean cacheEntrySerializerFound = false; for (Class clazz : typeMap.keySet()) { if (clazz == CacheKey.class) { cacheKeySerializerFound = true; } else if (clazz == CacheEntry.class) { cacheEntrySerializerFound = true; } } assertTrue("CacheKey serializer not found", cacheKeySerializerFound); assertTrue("CacheEntry serializer not found", cacheEntrySerializerFound); }
private boolean isCached( EntityKey entityKey, EntityPersister persister, EntityMode entityMode) { if ( persister.hasCache() ) { CacheKey key = new CacheKey( entityKey.getIdentifier(), persister.getIdentifierType(), entityKey.getEntityName(), entityMode, context.getSession().getFactory() ); return persister.getCache().getCache().get( key ) != null; } return false; }
private boolean isCached( Serializable collectionKey, CollectionPersister persister, EntityMode entityMode) { if ( persister.hasCache() ) { CacheKey cacheKey = new CacheKey( collectionKey, persister.getKeyType(), persister.getRole(), entityMode, context.getSession().getFactory() ); return persister.getCache().getCache().get( cacheKey ) != null; } return false; }
public void afterTransactionCompletion(boolean success) throws HibernateException { EntityPersister persister = getPersister(); if ( success && isCachePutEnabled( persister, getSession() ) ) { final CacheKey ck = new CacheKey( getId(), persister.getIdentifierType(), persister.getRootEntityName(), getSession().getEntityMode(), getSession().getFactory() ); boolean put = persister.getCache().afterInsert(ck, cacheEntry, version ); if ( put && getSession().getFactory().getStatistics().isStatisticsEnabled() ) { getSession().getFactory().getStatisticsImplementor() .secondLevelCachePut( getPersister().getCache().getRegionName() ); } } postCommitInsert(); }
public final void beforeExecutions() throws CacheException { // we need to obtain the lock before any actions are // executed, since this may be an inverse="true" // bidirectional association and it is one of the // earlier entity actions which actually updates // the database (this action is resposible for // second-level cache invalidation only) if ( persister.hasCache() ) { final CacheKey ck = new CacheKey( key, persister.getKeyType(), persister.getRole(), session.getEntityMode(), session.getFactory() ); lock = persister.getCache().lock(ck, null); } }
public void afterTransactionCompletion(boolean success) throws CacheException { EntityPersister persister = getPersister(); if ( persister.hasCache() ) { final CacheKey ck = new CacheKey( getId(), persister.getIdentifierType(), persister.getRootEntityName(), getSession().getEntityMode(), getSession().getFactory() ); if ( success && cacheEntry!=null /*!persister.isCacheInvalidationRequired()*/ ) { boolean put = persister.getCache().afterUpdate(ck, cacheEntry, nextVersion, lock ); if ( put && getSession().getFactory().getStatistics().isStatisticsEnabled() ) { getSession().getFactory().getStatisticsImplementor() .secondLevelCachePut( getPersister().getCache().getRegionName() ); } } else { persister.getCache().release(ck, lock ); } } postCommitUpdate(); }
protected static boolean isCached( PersistenceContext context, Serializable collectionKey, CollectionPersister persister, EntityMode entityMode) { if ( persister.hasCache() ) { CacheKey cacheKey = new CacheKey( collectionKey, persister.getKeyType(), persister.getRole(), entityMode, context.getSession().getFactory() ); return persister.getCacheAccessStrategy().get( cacheKey, context.getSession().getTimestamp() ) != null; } return false; }
public Object initializeLazyProperty(String fieldName, Object entity, SessionImplementor session) throws HibernateException { final Serializable id = session.getContextEntityIdentifier( entity ); final EntityEntry entry = session.getPersistenceContext().getEntry( entity ); if ( entry == null ) { throw new HibernateException( "entity is not associated with the session: " + id ); } if ( log.isTraceEnabled() ) { log.trace( "initializing lazy properties of: " + MessageHelper.infoString( this, id, getFactory() ) + ", field access: " + fieldName ); } if ( hasCache() ) { CacheKey cacheKey = new CacheKey(id, getIdentifierType(), getEntityName(), session.getEntityMode(), getFactory() ); Object ce = getCache().get( cacheKey, session.getTimestamp() ); if (ce!=null) { CacheEntry cacheEntry = (CacheEntry) getCacheEntryStructure().destructure(ce, factory); if ( !cacheEntry.areLazyPropertiesUnfetched() ) { //note early exit here: return initializeLazyPropertiesFromCache( fieldName, entity, session, entry, cacheEntry ); } } } return initializeLazyPropertiesFromDatastore( fieldName, entity, session, id, entry ); }
public Map getEntries() { Map map = new HashMap(); Iterator iter = cache.toMap().entrySet().iterator(); while ( iter.hasNext() ) { Map.Entry me = (Map.Entry) iter.next(); map.put( ( (CacheKey) me.getKey() ).getKey(), me.getValue() ); } return map; }
public void evictEntity(String entityName, Serializable id) throws HibernateException { EntityPersister p = getEntityPersister(entityName); if ( p.hasCache() ) { if ( log.isDebugEnabled() ) { log.debug( "evicting second-level cache: " + MessageHelper.infoString(p, id, this) ); } CacheKey cacheKey = new CacheKey( id, p.getIdentifierType(), p.getRootEntityName(), EntityMode.POJO, this ); p.getCache().remove( cacheKey ); } }
public void evict(Class persistentClass, Serializable id) throws HibernateException { EntityPersister p = getEntityPersister( persistentClass.getName() ); if ( p.hasCache() ) { if ( log.isDebugEnabled() ) { log.debug( "evicting second-level cache: " + MessageHelper.infoString(p, id, this) ); } CacheKey cacheKey = new CacheKey( id, p.getIdentifierType(), p.getRootEntityName(), EntityMode.POJO, this ); p.getCache().remove( cacheKey ); } }
public void evictCollection(String roleName, Serializable id) throws HibernateException { CollectionPersister p = getCollectionPersister(roleName); if ( p.hasCache() ) { if ( log.isDebugEnabled() ) { log.debug( "evicting second-level cache: " + MessageHelper.collectionInfoString(p, id, this) ); } CacheKey cacheKey = new CacheKey( id, p.getKeyType(), p.getRole(), EntityMode.POJO, this ); p.getCache().remove( cacheKey ); } }
public void afterTransactionCompletion(boolean success) throws HibernateException { if ( getPersister().hasCache() ) { final CacheKey ck = new CacheKey( getId(), getPersister().getIdentifierType(), getPersister().getRootEntityName(), getSession().getEntityMode(), getSession().getFactory() ); getPersister().getCache().release(ck, lock); } postCommitDelete(); }
public void execute() throws HibernateException { EntityPersister persister = getPersister(); SessionImplementor session = getSession(); Object instance = getInstance(); Serializable id = getId(); boolean veto = preInsert(); // Don't need to lock the cache here, since if someone // else inserted the same pk first, the insert would fail if ( !veto ) { persister.insert( id, state, instance, session ); EntityEntry entry = session.getPersistenceContext().getEntry( instance ); if ( entry == null ) { throw new AssertionFailure( "possible nonthreadsafe access to session" ); } entry.postInsert(); if ( persister.hasInsertGeneratedProperties() ) { persister.processInsertGeneratedProperties( id, instance, state, session ); if ( persister.isVersionPropertyGenerated() ) { version = Versioning.getVersion(state, persister); } entry.postUpdate(instance, state, version); } } final SessionFactoryImplementor factory = getSession().getFactory(); if ( isCachePutEnabled( persister, session ) ) { CacheEntry ce = new CacheEntry( state, persister, persister.hasUninitializedLazyProperties( instance, session.getEntityMode() ), version, session, instance ); cacheEntry = persister.getCacheEntryStructure().structure(ce); final CacheKey ck = new CacheKey( id, persister.getIdentifierType(), persister.getRootEntityName(), session.getEntityMode(), session.getFactory() ); // boolean put = persister.getCache().insert(ck, cacheEntry); boolean put = persister.getCache().insert( ck, cacheEntry, version ); if ( put && factory.getStatistics().isStatisticsEnabled() ) { factory.getStatisticsImplementor() .secondLevelCachePut( getPersister().getCache().getRegionName() ); } } postInsert(); if ( factory.getStatistics().isStatisticsEnabled() && !veto ) { factory.getStatisticsImplementor() .insertEntity( getPersister().getEntityName() ); } }
public void afterTransactionCompletion(boolean success) throws CacheException { if ( persister.hasCache() ) { final CacheKey ck = new CacheKey( key, persister.getKeyType(), persister.getRole(), session.getEntityMode(), session.getFactory() ); persister.getCache().release(ck, lock); } }
protected final void evict() throws CacheException { if ( persister.hasCache() ) { CacheKey ck = new CacheKey( key, persister.getKeyType(), persister.getRole(), session.getEntityMode(), session.getFactory() ); persister.getCache().evict(ck); } }
@Test public void testAutoregistrationOnHibernate3NonAvailable() throws Exception { Thread thread = Thread.currentThread(); ClassLoader tccl = thread.getContextClassLoader(); Object config = null; Method setClassLoader = null; try { thread.setContextClassLoader(FILTERING_CLASS_LOADER); Class<?> configClazz = FILTERING_CLASS_LOADER.loadClass("com.hazelcast.config.Config"); config = configClazz.newInstance(); setClassLoader = configClazz.getDeclaredMethod("setClassLoader", ClassLoader.class); setClassLoader.invoke(config, FILTERING_CLASS_LOADER); Class<?> hazelcastClazz = FILTERING_CLASS_LOADER.loadClass("com.hazelcast.core.Hazelcast"); Method newHazelcastInstance = hazelcastClazz.getDeclaredMethod("newHazelcastInstance", configClazz); Object hz = newHazelcastInstance.invoke(hazelcastClazz, config); Object impl = ORIGINAL.get(hz); Object serializationService = GET_SERIALIZATION_SERVICE.invoke(impl); //noinspection unchecked ConcurrentMap<Class, ?> typeMap = (ConcurrentMap<Class, ?>) TYPE_MAP.get(serializationService); boolean cacheKeySerializerFound = false; boolean cacheEntrySerializerFound = false; for (Class clazz : typeMap.keySet()) { if (clazz == CacheKey.class) { cacheKeySerializerFound = true; } else if (clazz == CacheEntry.class) { cacheEntrySerializerFound = true; } } hazelcastClazz.getDeclaredMethod("shutdownAll").invoke(impl); assertFalse("CacheKey serializer found", cacheKeySerializerFound); assertFalse("CacheEntry serializer found", cacheEntrySerializerFound); } finally { if (config != null && setClassLoader != null) { setClassLoader.invoke(config, tccl); } thread.setContextClassLoader(tccl); } }
/** * Add the collection to the second-level cache * * @param lce The entry representing the collection to add * @param persister The persister */ private void addCollectionToCache(LoadingCollectionEntry lce, CollectionPersister persister) { final SessionImplementor session = getLoadContext().getPersistenceContext().getSession(); final SessionFactoryImplementor factory = session.getFactory(); if ( log.isDebugEnabled() ) { log.debug( "Caching collection: " + MessageHelper.collectionInfoString( persister, lce.getKey(), factory ) ); } if ( !session.getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( session ) ) { // some filters affecting the collection are enabled on the session, so do not do the put into the cache. log.debug( "Refusing to add to cache due to enabled filters" ); // todo : add the notion of enabled filters to the CacheKey to differentiate filtered collections from non-filtered; // but CacheKey is currently used for both collections and entities; would ideally need to define two seperate ones; // currently this works in conjuction with the check on // DefaultInitializeCollectionEventHandler.initializeCollectionFromCache() (which makes sure to not read from // cache with enabled filters). return; // EARLY EXIT!!!!! } final Comparator versionComparator; final Object version; if ( persister.isVersioned() ) { versionComparator = persister.getOwnerEntityPersister().getVersionType().getComparator(); final Object collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner( lce.getKey(), persister ); version = getLoadContext().getPersistenceContext().getEntry( collectionOwner ).getVersion(); } else { version = null; versionComparator = null; } CollectionCacheEntry entry = new CollectionCacheEntry( lce.getCollection(), persister ); CacheKey cacheKey = new CacheKey( lce.getKey(), persister.getKeyType(), persister.getRole(), session.getEntityMode(), session.getFactory() ); boolean put = persister.getCache().put( cacheKey, persister.getCacheEntryStructure().structure(entry), session.getTimestamp(), version, versionComparator, factory.getSettings().isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH ); if ( put && factory.getStatistics().isStatisticsEnabled() ) { factory.getStatisticsImplementor().secondLevelCachePut( persister.getCache().getRegionName() ); } }
/** * Try to initialize a collection from the cache */ private boolean initializeCollectionFromCache( Serializable id, CollectionPersister persister, PersistentCollection collection, SessionImplementor source) throws HibernateException { if ( !source.getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( source ) ) { log.trace( "disregarding cached version (if any) of collection due to enabled filters "); return false; } final boolean useCache = persister.hasCache() && source.getCacheMode().isGetEnabled(); if ( !useCache ) { return false; } else { final SessionFactoryImplementor factory = source.getFactory(); final CacheKey ck = new CacheKey( id, persister.getKeyType(), persister.getRole(), source.getEntityMode(), source.getFactory() ); Object ce = persister.getCache().get( ck, source.getTimestamp() ); if ( factory.getStatistics().isStatisticsEnabled() ) { if (ce==null) { factory.getStatisticsImplementor().secondLevelCacheMiss( persister.getCache().getRegionName() ); } else { factory.getStatisticsImplementor().secondLevelCacheHit( persister.getCache().getRegionName() ); } } if (ce==null) { return false; } else { CollectionCacheEntry cacheEntry = (CollectionCacheEntry) persister.getCacheEntryStructure() .destructure(ce, factory); final PersistenceContext persistenceContext = source.getPersistenceContext(); cacheEntry.assemble( collection, persister, persistenceContext.getCollectionOwner(id, persister) ); persistenceContext.getCollectionEntry(collection).postInitialize(collection); //addInitializedCollection(collection, persister, id); return true; } } }
/** * Attempts to load the entity from the second-level cache. * * @param event The load event * @param persister The persister for the entity being requested for load * @param options The load options. * @return The entity from the second-level cache, or null. * @throws HibernateException */ protected Object loadFromSecondLevelCache( final LoadEvent event, final EntityPersister persister, final LoadEventListener.LoadType options) throws HibernateException { final SessionImplementor source = event.getSession(); final boolean useCache = persister.hasCache() && source.getCacheMode().isGetEnabled() && event.getLockMode().lessThan(LockMode.READ); if (useCache) { final SessionFactoryImplementor factory = source.getFactory(); final CacheKey ck = new CacheKey( event.getEntityId(), persister.getIdentifierType(), persister.getRootEntityName(), source.getEntityMode(), source.getFactory() ); Object ce = persister.getCache() .get( ck, source.getTimestamp() ); if ( factory.getStatistics().isStatisticsEnabled() ) { if (ce==null) { factory.getStatisticsImplementor().secondLevelCacheMiss( persister.getCache().getRegionName() ); } else { factory.getStatisticsImplementor().secondLevelCacheHit( persister.getCache().getRegionName() ); } } if ( ce != null ) { CacheEntry entry = (CacheEntry) persister.getCacheEntryStructure() .destructure(ce, factory); // Entity was found in second-level cache... return assembleCacheEntry( entry, event.getEntityId(), persister, event ); } } return null; }
public void refresh(String entityName, Object entity, LockMode lockMode) { final EntityPersister persister = this.getEntityPersister( entityName, entity ); final Serializable id = persister.getIdentifier( entity, getEntityMode() ); if ( log.isTraceEnabled() ) { log.trace( "refreshing transient " + MessageHelper.infoString( persister, id, this.getFactory() ) ); } // TODO : can this ever happen??? // EntityKey key = new EntityKey( id, persister, source.getEntityMode() ); // if ( source.getPersistenceContext().getEntry( key ) != null ) { // throw new PersistentObjectException( // "attempted to refresh transient instance when persistent " + // "instance was already associated with the Session: " + // MessageHelper.infoString( persister, id, source.getFactory() ) // ); // } if ( persister.hasCache() ) { final CacheKey ck = new CacheKey( id, persister.getIdentifierType(), persister.getRootEntityName(), this.getEntityMode(), this.getFactory() ); persister.getCache().remove(ck); } String previousFetchProfile = this.getFetchProfile(); Object result = null; try { this.setFetchProfile( "refresh" ); result = persister.load( id, entity, lockMode, this ); } finally { this.setFetchProfile( previousFetchProfile ); } UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() ); }
public void testSecondLevelCachedCollectionsFiltering() { TestData testData = new TestData(); testData.prepare(); Session session = openSession(); // Force a collection into the second level cache, with its non-filtered elements Salesperson sp = ( Salesperson ) session.load( Salesperson.class, testData.steveId ); Hibernate.initialize( sp.getOrders() ); CollectionPersister persister = ( ( SessionFactoryImpl ) getSessions() ) .getCollectionPersister( Salesperson.class.getName() + ".orders" ); assertTrue( "No cache for collection", persister.hasCache() ); CollectionCacheEntry cachedData = ( CollectionCacheEntry ) persister.getCache().getCache() .read( new CacheKey( testData.steveId, persister.getKeyType(), persister.getRole(), EntityMode.POJO, sfi() ) ); assertNotNull( "collection was not in cache", cachedData ); session.close(); session = openSession(); session.enableFilter( "fulfilledOrders" ).setParameter( "asOfDate", testData.lastMonth.getTime() ); sp = ( Salesperson ) session.createQuery( "from Salesperson as s where s.id = :id" ) .setLong( "id", testData.steveId.longValue() ) .uniqueResult(); assertEquals( "Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size() ); CollectionCacheEntry cachedData2 = ( CollectionCacheEntry ) persister.getCache().getCache() .read( new CacheKey( testData.steveId, persister.getKeyType(), persister.getRole(), EntityMode.POJO, sfi() ) ); assertNotNull( "collection no longer in cache!", cachedData2 ); assertSame( "Different cache values!", cachedData, cachedData2 ); session.close(); session = openSession(); session.enableFilter( "fulfilledOrders" ).setParameter( "asOfDate", testData.lastMonth.getTime() ); sp = ( Salesperson ) session.load( Salesperson.class, testData.steveId ); assertEquals( "Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size() ); session.close(); // Finally, make sure that the original cached version did not get over-written session = openSession(); sp = ( Salesperson ) session.load( Salesperson.class, testData.steveId ); assertEquals( "Actual cached version got over-written", 2, sp.getOrders().size() ); session.close(); testData.release(); }