The entity instance is already in the session cache

Copied from Loader#instanceAlreadyLoaded
327990
private void instanceAlreadyLoaded(
		final Tuple resultset,
		final int i,
			//TODO create an interface for this usage
		final OgmEntityPersister persister,
		final org.hibernate.engine.spi.EntityKey key,
		final Object object,
		final LockMode lockMode,
		final SharedSessionContractImplementor session)
	throws HibernateException {
		if ( !persister.isInstance( object ) ) {
			throw new WrongClassException(
					"loaded object was of wrong class " + object.getClass(),
					key.getIdentifier(),
					persister.getEntityName()
				);
		}

		if ( LockMode.NONE != lockMode && upgradeLocks() ) { // no point doing this if NONE was requested

			final boolean isVersionCheckNeeded = persister.isVersioned() &&
					session.getPersistenceContext().getEntry( object )
							.getLockMode().lessThan( lockMode );
			// we don't need to worry about existing version being uninitialized
			// because this block isn't called by a re-entrant load (re-entrant
			// loads _always_ have lock mode NONE)
			if ( isVersionCheckNeeded ) {
				//we only check the version when _upgrading_ lock modes
				Object oldVersion = session.getPersistenceContext().getEntry( object ).getVersion();
				persister.checkVersionAndRaiseSOSE( key.getIdentifier(), oldVersion, session, resultset );
				//we need to upgrade the lock mode to the mode requested
				session.getPersistenceContext().getEntry( object )
						.setLockMode( lockMode );
			}
		}
	}
253457
@Override
	public CProduct fetchByPrimaryKey(Serializable primaryKey) {
		Serializable serializable = entityCache.getResult(CProductModelImpl.ENTITY_CACHE_ENABLED,
				CProductImpl.class, primaryKey);

		if (serializable == nullModel) {
			return null;
		}

		CProduct cProduct = (CProduct)serializable;

		if (cProduct == null) {
			Session session = null;

			try {
				session = openSession();

				cProduct = (CProduct)session.get(CProductImpl.class, primaryKey);

				if (cProduct != null) {
					cacheResult(cProduct);
				}
				else {
					entityCache.putResult(CProductModelImpl.ENTITY_CACHE_ENABLED,
						CProductImpl.class, primaryKey, nullModel);
				}
			}
			catch (Exception e) {
				entityCache.removeResult(CProductModelImpl.ENTITY_CACHE_ENABLED,
					CProductImpl.class, primaryKey);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return cProduct;
	}
77227
public static void init(Context context, String name, int version, int cacheSize, LogLevel logLevel) {
		sLogLevel = logLevel;

		if (sInitialized) {
			if (sLogLevel.log(LogLevel.BASIC)) {
				Log.d(TAG, "Already initialized.");
			}
			return;
		}

		try {
			Class adapterClass = Class.forName(AdapterHolder.IMPL_CLASS_FQCN);
			sAdapterHolder = (AdapterHolder) adapterClass.newInstance();
		} catch (Exception e) {
			if (sLogLevel.log(LogLevel.BASIC)) {
				Log.e(TAG, "Failed to initialize.", e);
			}
		}

		sContext = context.getApplicationContext();
		sDatabaseHelper = new DatabaseHelper(sContext, name, version);
		sSQLiteDatabase = sDatabaseHelper.getWritableDatabase();
		sCache = new LruCache<String, Model>(cacheSize);

		sInitialized = true;
	}
803320
def update_cache_for_instance(
        model_name, instance_pk, instance=None, version=None):
    """"""
    cache = SampleCache()
    invalid = cache.update_instance(model_name, instance_pk, instance, version)
    for invalid_name, invalid_pk, invalid_version in invalid:
        update_cache_for_instance.delay(
            invalid_name, invalid_pk, version=invalid_version)
1208767
@Override
	public void cacheResult(CommerceVirtualOrderItem commerceVirtualOrderItem) {
		entityCache.putResult(CommerceVirtualOrderItemModelImpl.ENTITY_CACHE_ENABLED,
			CommerceVirtualOrderItemImpl.class,
			commerceVirtualOrderItem.getPrimaryKey(), commerceVirtualOrderItem);

		finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
			new Object[] {
				commerceVirtualOrderItem.getUuid(),
				commerceVirtualOrderItem.getGroupId()
			}, commerceVirtualOrderItem);

		finderCache.putResult(FINDER_PATH_FETCH_BY_COMMERCEORDERITEMID,
			new Object[] { commerceVirtualOrderItem.getCommerceOrderItemId() },
			commerceVirtualOrderItem);

		commerceVirtualOrderItem.resetOriginalValues();
	}
692774
public static void initialize(final Class<?> _class)
        throws CacheReloadException
    {
        if (InfinispanCache.get().exists(Type.UUIDCACHE)) {
            InfinispanCache.get().<UUID, Type>getCache(Type.UUIDCACHE).clear();
        } else {
            InfinispanCache.get().<UUID, Type>getCache(Type.UUIDCACHE).addListener(new CacheLogListener(Type.LOG));
        }
        if (InfinispanCache.get().exists(Type.IDCACHE)) {
            InfinispanCache.get().<Long, Type>getCache(Type.IDCACHE).clear();
        } else {
            InfinispanCache.get().<Long, Type>getCache(Type.IDCACHE).addListener(new CacheLogListener(Type.LOG));
        }
        if (InfinispanCache.get().exists(Type.NAMECACHE)) {
            InfinispanCache.get().<String, Type>getCache(Type.NAMECACHE).clear();
        } else {
            InfinispanCache.get().<String, Type>getCache(Type.NAMECACHE).addListener(new CacheLogListener(Type.LOG));
        }
        if (InfinispanCache.get().exists(EnumType.CACHE)) {
            InfinispanCache.get().getCache(EnumType.CACHE).clear();
        }
        QueryCache.initialize();
    }
260903
function () {
    var el;
    if (this.availableEls.length === 0) {
      if (this.data.dynamic === false) {
        warn('Requested entity from empty pool: ' + this.attrName);
        return;
      } else {
        warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
             'automatically. You might want to increase its initial size: ' + this.attrName);
      }
      this.createEntity();
    }
    el = this.availableEls.shift();
    this.usedEls.push(el);
    el.object3D.visible = true;
    return el;
  }
451777
private void loadFromResultSet(
		final Tuple resultset,
		final int i,
		final Object object,
		final String instanceEntityName,
		final org.hibernate.engine.spi.EntityKey key,
		final String rowIdAlias,
		final LockMode lockMode,
		final Loadable rootPersister,
		final SharedSessionContractImplementor session)
	throws HibernateException {

		final Serializable id = key.getIdentifier();

		// Get the persister for the _subclass_
		final OgmEntityPersister persister = (OgmEntityPersister) getFactory().getMetamodel().entityPersister( instanceEntityName );

		if ( log.isTraceEnabled() ) {
			log.trace(
					"Initializing object from ResultSet: " +
					MessageHelper.infoString( persister, id, getFactory() )
				);
		}

		//FIXME figure out what that means and what value should be set
		//boolean eagerPropertyFetch = isEagerPropertyFetchEnabled(i);
		boolean fetchAllPropertiesRequested = true;

		// add temp entry so that the next step is circular-reference
		// safe - only needed because some types don't take proper
		// advantage of two-phase-load (esp. components)
		TwoPhaseLoad.addUninitializedEntity(
				key,
				object,
				persister,
				lockMode,
				session
		);

		//TODO what to do with that in OGM
//		//This is not very nice (and quite slow):
//		final String[][] cols = persister == rootPersister ?
//				getEntityAliases()[i].getSuffixedPropertyAliases() :
//				getEntityAliases()[i].getSuffixedPropertyAliases(persister);

		final Object[] values = persister.hydrate(
				resultset,
				id,
				object,
				rootPersister,
				//cols,
				fetchAllPropertiesRequested,
				session
			);

		if ( persister.hasRowId() ) {
			throw new HibernateException( "Hibernate OGM does not support row id" );
		}
		final Object rowId = null;

		final AssociationType[] ownerAssociationTypes = getOwnerAssociationTypes();
		if ( ownerAssociationTypes != null && ownerAssociationTypes[i] != null ) {
			String ukName = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName();
			if ( ukName != null ) {
				final int index = ( (UniqueKeyLoadable) persister ).getPropertyIndex( ukName );
				final Type type = persister.getPropertyTypes()[index];

				// polymorphism not really handled completely correctly,
				// perhaps...well, actually its ok, assuming that the
				// entity name used in the lookup is the same as the
				// the one used here, which it will be

				EntityUniqueKey euk = new EntityUniqueKey(
						rootPersister.getEntityName(), //polymorphism comment above
						ukName,
						type.semiResolve( values[index], session, object ),
						type,
						persister.getEntityMode(),
						session.getFactory()
					);
				session.getPersistenceContext().addEntity( euk, object );
			}
		}

		TwoPhaseLoad.postHydrate(
				persister,
				id,
				values,
				rowId,
				object,
				lockMode,
				session
			);

		OgmEntityEntryState.getStateFor( session, object ).getTuplePointer().setTuple( resultset );
	}
1006799
private MemcachedBackupSession loadFromMemcached( final String sessionId ) {
        if ( _log.isDebugEnabled() ) {
            _log.debug( "Loading session from memcached: " + sessionId );
        }

        LockStatus lockStatus = null;
        try {

            if ( !_sticky ) {
                lockStatus = _lockingStrategy.onBeforeLoadFromMemcached( sessionId );
            }

            final long start = System.currentTimeMillis();

            /* In the previous version (<1.2) the session was completely serialized by
             * custom Transcoder implementations.
             * Such sessions have set the SERIALIZED flag (from SerializingTranscoder) so that
             * they get deserialized by BaseSerializingTranscoder.deserialize or the appropriate
             * specializations.
             */
            final byte[] object = _storage.get( _memcachedNodesManager.getStorageKeyFormat().format( sessionId ) );
            _memcachedNodesManager.onLoadFromMemcachedSuccess( sessionId );

            if ( object != null ) {
                final long startDeserialization = System.currentTimeMillis();
                final MemcachedBackupSession result = _transcoderService.deserialize( object, _manager );
                _statistics.registerSince( SESSION_DESERIALIZATION, startDeserialization );
                _statistics.registerSince( LOAD_FROM_MEMCACHED, start );

                result.setSticky( _sticky );
                if ( !_sticky ) {
                    _lockingStrategy.onAfterLoadFromMemcached( result, lockStatus );
                }

                if ( _log.isDebugEnabled() ) {
                    _log.debug( "Found session with id " + sessionId );
                }
                return result;
            }
            else {
                releaseIfLocked( sessionId, lockStatus );
                _invalidSessionsCache.put( sessionId, Boolean.TRUE );
                if ( _log.isDebugEnabled() ) {
                    _log.debug( "Session " + sessionId + " not found in memcached." );
                }
                return null;
            }
        } catch ( final TranscoderDeserializationException e ) {
            _log.warn( "Could not deserialize session with id " + sessionId + " from memcached, session will be purged from storage.", e );
            releaseIfLocked( sessionId, lockStatus );
            _storage.delete( _memcachedNodesManager.getStorageKeyFormat().format(sessionId) );
            _invalidSessionsCache.put( sessionId, Boolean.TRUE );
        } catch ( final Exception e ) {
            _log.warn( "Could not load session with id " + sessionId + " from memcached.", e );
            releaseIfLocked( sessionId, lockStatus );
        } finally {
        }
        return null;
    }
433668
public static void initialize()
        throws CacheReloadException
    {
        if (InfinispanCache.get().exists(Store.UUIDCACHE)) {
            InfinispanCache.get().<UUID, Store>getCache(Store.UUIDCACHE).clear();
        } else {
            InfinispanCache.get().<UUID, Store>getCache(Store.UUIDCACHE).addListener(new CacheLogListener(Store.LOG));
        }
        if (InfinispanCache.get().exists(Store.IDCACHE)) {
            InfinispanCache.get().<Long, Store>getCache(Store.IDCACHE).clear();
        } else {
            InfinispanCache.get().<Long, Store>getCache(Store.IDCACHE).addListener(new CacheLogListener(Store.LOG));
        }
        if (InfinispanCache.get().exists(Store.NAMECACHE)) {
            InfinispanCache.get().<String, Store>getCache(Store.NAMECACHE).clear();
        } else {
            InfinispanCache.get().<String, Store>getCache(Store.NAMECACHE).addListener(new CacheLogListener(Store.LOG));
        }
    }
108979
@Override
  public IRoSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientRoSession.class)) {
      ClientRoSessionDataReplicatedImpl data =
          new ClientRoSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
      return data;
    }
    else if (clazz.equals(ServerRoSession.class)) {
      ServerRoSessionDataReplicatedImpl data = new ServerRoSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
      return data;
    }
    throw new IllegalArgumentException();
  }
903783
@Override
	public UniqueEntityLoader getAppropriateLoader(LockOptions lockOptions, SharedSessionContractImplementor session) {
//		if ( queryLoader != null ) {
//			// if the user specified a custom query loader we need to that
//			// regardless of any other consideration
//			return queryLoader;
//		}
//		else if ( isAffectedByEnabledFilters( session ) ) {
//			// because filters affect the rows returned (because they add
//			// restrictions) these need to be next in precedence
//			return createEntityLoader(lockOptions, session.getLoadQueryInfluencers() );
//		}
//		else if ( session.getLoadQueryInfluencers().getInternalFetchProfile() != null && LockMode.UPGRADE.greaterThan( lockOptions.getLockMode() ) ) {
//			// Next, we consider whether an 'internal' fetch profile has been set.
//			// This indicates a special fetch profile Hibernate needs applied
//			// (for its merge loading process e.g.).
//			return ( UniqueEntityLoader ) getLoaders().get( session.getLoadQueryInfluencers().getInternalFetchProfile() );
//		}
//		else if ( isAffectedByEnabledFetchProfiles( session ) ) {
//			// If the session has associated influencers we need to adjust the
//			// SQL query used for loading based on those influencers
//			return createEntityLoader(lockOptions, session.getLoadQueryInfluencers() );
//		}
//		else if ( isAffectedByEntityGraph( session ) ) {
//			return createEntityLoader( lockOptions, session.getLoadQueryInfluencers() );
//		}
//		else if ( lockOptions.getTimeOut() != LockOptions.WAIT_FOREVER ) {
//			return createEntityLoader( lockOptions, session.getLoadQueryInfluencers() );
//		}
//		else {
//			return ( UniqueEntityLoader ) getLoaders().get( lockOptions.getLockMode() );
//		}
		// Today OGM cannot really react to all the use cases commented
		return (UniqueEntityLoader) getLoaders().get( lockOptions.getLockMode() );
	}
1144164
void init(long index, Instant instant, ServerStateMachineContext.Type type) {
    context.update(index, instant, type);
  }
1256002
private void load2Entity(Object entity, Method setMethod, Object value) throws Exception {
        try {
            if (value != null) {
                setMethod.invoke(entity, value);
            }
        } catch (Exception e) {
            String sValue = value.toString();
            String sValueClass = value.getClass().toString();
            System.out.println("Error in " + setMethod.getName() + " invoke with param :" + sValue + " type is " +
                    sValueClass);
            throw e;
        }
    }
1053347
public static void reloadInstance(CFMLEngine engine, ConfigServerImpl cs, ConfigWebImpl cw, boolean force)
	    throws SAXException, ClassException, PageException, IOException, TagLibException, FunctionLibException, BundleException {
	Resource configFile = cw.getConfigFile();
	Resource configDir = cw.getConfigDir();

	int iDoNew = doNew(engine, configDir, false).updateType;
	boolean doNew = iDoNew != NEW_NONE;

	if (configFile == null) return;

	if (second(cw.getLoadTime()) > second(configFile.lastModified()) && !force) return;

	Document doc = loadDocument(configFile);
	createContextFiles(configDir, null, doNew);
	cw.reset();
	load(cs, cw, doc, true, doNew);
	createContextFilesPost(configDir, cw, null, false, doNew);

	((CFMLEngineImpl) ConfigWebUtil.getEngine(cw)).onStart(cw, true);
    }
497182
def reload(options = nil)
      clear_aggregation_cache
      clear_association_cache

      IdentityMap.without do
        fresh_object = self.class.unscoped { self.class.find(self.id, options) }
        @attributes.update(fresh_object.instance_variable_get('@attributes'))
      end

      @attributes_cache = {}
      self
    end
400940
private LoadingCache<Object, Optional<Map<String, Object>>> createEntityCache(
      Repository<Entity> repository) {
    Caffeine<Object, Object> cacheBuilder =
        Caffeine.newBuilder().recordStats().expireAfterAccess(10, MINUTES);
    if (!MetaDataService.isMetaEntityType(repository.getEntityType())) {
      cacheBuilder.maximumSize(MAX_CACHE_SIZE_PER_ENTITY);
    }
    LoadingCache<Object, Optional<Map<String, Object>>> cache =
        CaffeinatedGuava.build(cacheBuilder, createCacheLoader(repository));
    GuavaCacheMetrics.monitor(meterRegistry, cache, "l2." + repository.getEntityType().getId());
    return cache;
  }