org.hibernate.collection.spi.PersistentCollection#wasInitialized ( )源码实例Demo

下面列出了org.hibernate.collection.spi.PersistentCollection#wasInitialized ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hibernate-reactive   文件: Cascade.java
/**
 * Delete any entities that were removed from the collection
 */
private void deleteOrphans(String entityName, PersistentCollection pc) throws HibernateException {
	//TODO: suck this logic into the collection!
	final Collection<?> orphans;
	if ( pc.wasInitialized() ) {
		final CollectionEntry ce = eventSource.getPersistenceContextInternal().getCollectionEntry( pc );
		orphans = ce==null
				? Collections.EMPTY_LIST
				: ce.getOrphans( entityName, pc );
	}
	else {
		orphans = pc.getQueuedOrphans( entityName );
	}

	for ( Object orphan : orphans ) {
		if ( orphan != null ) {
			LOG.tracev( "Deleting orphaned entity instance: {0}", entityName );
			eventSource.delete( entityName, orphan, false, new HashSet<>() );
		}
	}
}
 
源代码2 项目: lams   文件: Cascade.java
/**
 * Delete any entities that were removed from the collection
 */
private static void deleteOrphans(EventSource eventSource, String entityName, PersistentCollection pc) throws HibernateException {
	//TODO: suck this logic into the collection!
	final Collection orphans;
	if ( pc.wasInitialized() ) {
		final CollectionEntry ce = eventSource.getPersistenceContext().getCollectionEntry( pc );
		orphans = ce==null
				? java.util.Collections.EMPTY_LIST
				: ce.getOrphans( entityName, pc );
	}
	else {
		orphans = pc.getQueuedOrphans( entityName );
	}

	for ( Object orphan : orphans ) {
		if ( orphan != null ) {
			LOG.tracev( "Deleting orphaned entity instance: {0}", entityName );
			eventSource.delete( entityName, orphan, false, new HashSet() );
		}
	}
}
 
源代码3 项目: lams   文件: CollectionEntry.java
/**
 * Determine if the collection is "really" dirty, by checking dirtiness
 * of the collection elements, if necessary
 */
private void dirty(PersistentCollection collection) throws HibernateException {

	boolean forceDirty = collection.wasInitialized() &&
			!collection.isDirty() && //optimization
			getLoadedPersister() != null &&
			getLoadedPersister().isMutable() && //optimization
			( collection.isDirectlyAccessible() || getLoadedPersister().getElementType().isMutable() ) && //optimization
			!collection.equalsSnapshot( getLoadedPersister() );

	if ( forceDirty ) {
		collection.dirty();
	}

}
 
源代码4 项目: lams   文件: CollectionEntry.java
/**
 * Called after execution of an action
 */
public void afterAction(PersistentCollection collection) {
	loadedKey = getCurrentKey();
	setLoadedPersister( getCurrentPersister() );

	boolean resnapshot = collection.wasInitialized() &&
			( isDoremove() || isDorecreate() || isDoupdate() );
	if ( resnapshot ) {
		snapshot = loadedPersister==null || !loadedPersister.isMutable() ?
				null :
				collection.getSnapshot(loadedPersister); //re-snapshot
	}

	collection.postAction();
}
 
源代码5 项目: lams   文件: CollectionEntry.java
public boolean isSnapshotEmpty(PersistentCollection collection) {
	//TODO: does this really need to be here?
	//      does the collection already have
	//      it's own up-to-date snapshot?
	return collection.wasInitialized() &&
		( getLoadedPersister()==null || getLoadedPersister().isMutable() ) &&
		collection.isSnapshotEmpty( getSnapshot() );
}
 
源代码6 项目: lams   文件: OnReplicateVisitor.java
@Override
public Object processCollection(Object collection, CollectionType type) throws HibernateException {
	if ( collection == CollectionType.UNFETCHED_COLLECTION ) {
		return null;
	}

	final EventSource session = getSession();
	final CollectionPersister persister = session.getFactory().getMetamodel().collectionPersister( type.getRole() );

	if ( isUpdate ) {
		removeCollection( persister, extractCollectionKeyFromOwner( persister ), session );
	}
	if ( collection != null && collection instanceof PersistentCollection ) {
		final PersistentCollection wrapper = (PersistentCollection) collection;
		wrapper.setCurrentSession( (SessionImplementor) session );
		if ( wrapper.wasInitialized() ) {
			session.getPersistenceContext().addNewCollection( persister, wrapper );
		}
		else {
			reattachCollection( wrapper, type );
		}
	}
	else {
		// otherwise a null or brand new collection
		// this will also (inefficiently) handle arrays, which
		// have no snapshot, so we can't do any better
		//processArrayOrNewCollection(collection, type);
	}

	return null;

}
 
源代码7 项目: gorm-hibernate5   文件: HibernateProxyHandler.java
public void initialize(Object o) {
    if (o instanceof PersistentCollection) {
        final PersistentCollection col = (PersistentCollection)o;
        if (!col.wasInitialized()) {
            col.forceInitialization();
        }
    }
    super.initialize(o);
}
 
/**
 * called by a collection that wants to initialize itself
 */
public CompletionStage<Void> onReactiveInitializeCollection(InitializeCollectionEvent event) throws HibernateException {
	PersistentCollection collection = event.getCollection();
	SessionImplementor source = event.getSession();

	CollectionEntry ce = source.getPersistenceContextInternal().getCollectionEntry( collection );
	if ( ce == null ) {
		throw new HibernateException( "collection was evicted" );
	}
	if ( !collection.wasInitialized() ) {
		final CollectionPersister ceLoadedPersister = ce.getLoadedPersister();
		if ( LOG.isTraceEnabled() ) {
			LOG.tracev( "Initializing collection {0}",
					MessageHelper.collectionInfoString( ceLoadedPersister, collection, ce.getLoadedKey(), source ) );
			LOG.trace( "Checking second-level cache" );
		}

		final boolean foundInCache = initializeCollectionFromCache( ce.getLoadedKey(), ceLoadedPersister, collection, source );

		if ( foundInCache ) {
			if ( LOG.isTraceEnabled() ) {
				LOG.trace( "Collection initialized from cache" );
			}
			return CompletionStages.nullFuture();
		}
		else {
			if ( LOG.isTraceEnabled() ) {
				LOG.trace( "Collection not cached" );
			}
			return ( (ReactiveOneToManyPersister) ceLoadedPersister ).reactiveInitialize( ce.getLoadedKey(), source )
					.thenAccept( list -> {
						if ( LOG.isTraceEnabled() ) {
							LOG.trace( "Collection initialized" );
						}

						final StatisticsImplementor statistics = source.getFactory().getStatistics();
						if ( statistics.isStatisticsEnabled() ) {
							statistics.fetchCollection( ceLoadedPersister.getRole() );
						}
					} );
		}
	}
	// Collection was already initialized.
	return CompletionStages.nullFuture();
}
 
源代码9 项目: lams   文件: BatchFetchQueue.java
/**
 * Get a batch of uninitialized collection keys for a given role
 *
 * @param collectionPersister The persister for the collection role.
 * @param id A key that must be included in the batch fetch
 * @param batchSize the maximum number of keys to return
 * @return an array of collection keys, of length batchSize (padded with nulls)
 */
public Serializable[] getCollectionBatch(
		final CollectionPersister collectionPersister,
		final Serializable id,
		final int batchSize) {

	Serializable[] keys = new Serializable[batchSize];
	keys[0] = id;

	int i = 1;
	int end = -1;
	boolean checkForEnd = false;

	final LinkedHashMap<CollectionEntry, PersistentCollection> map =  batchLoadableCollections.get( collectionPersister.getRole() );
	if ( map != null ) {
		for ( Entry<CollectionEntry, PersistentCollection> me : map.entrySet() ) {
			final CollectionEntry ce = me.getKey();
			final PersistentCollection collection = me.getValue();
			
			if ( ce.getLoadedKey() == null ) {
				// the loadedKey of the collectionEntry might be null as it might have been reset to null
				// (see for example Collections.processDereferencedCollection()
				// and CollectionEntry.afterAction())
				// though we clear the queue on flush, it seems like a good idea to guard
				// against potentially null loadedKeys (which leads to various NPEs as demonstrated in HHH-7821).
				continue;
			}

			if ( collection.wasInitialized() ) {
				// should never happen
				LOG.warn( "Encountered initialized collection in BatchFetchQueue, this should not happen." );
				continue;
			}

			if ( checkForEnd && i == end ) {
				return keys; //the first key found after the given key
			}

			final boolean isEqual = collectionPersister.getKeyType().isEqual(
					id,
					ce.getLoadedKey(),
					collectionPersister.getFactory()
			);

			if ( isEqual ) {
				end = i;
				//checkForEnd = false;
			}
			else if ( !isCached( ce.getLoadedKey(), collectionPersister ) ) {
				keys[i++] = ce.getLoadedKey();
				//count++;
			}

			if ( i == batchSize ) {
				i = 1; //end of array, start filling again from start
				if ( end != -1 ) {
					checkForEnd = true;
				}
			}
		}
	}
	return keys; //we ran out of keys to try
}
 
源代码10 项目: lams   文件: Collections.java
/**
    * Initialize the role of the collection.
    *
    * @param collection The collection to be updated by reachability.
    * @param type The type of the collection.
    * @param entity The owner of the collection.
 * @param session The session from which this request originates
    */
public static void processReachableCollection(
		PersistentCollection collection,
		CollectionType type,
		Object entity,
		SessionImplementor session) {
	collection.setOwner( entity );
	final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( collection );

	if ( ce == null ) {
		// refer to comment in StatefulPersistenceContext.addCollection()
		throw new HibernateException(
				"Found two representations of same collection: " +
				type.getRole()
		);
	}

	final SessionFactoryImplementor factory = session.getFactory();
	final CollectionPersister persister = factory.getMetamodel().collectionPersister( type.getRole() );

	ce.setCurrentPersister( persister );
	//TODO: better to pass the id in as an argument?
	ce.setCurrentKey( type.getKeyOfOwner( entity, session ) );

	final boolean isBytecodeEnhanced = persister.getOwnerEntityPersister().getInstrumentationMetadata().isEnhancedForLazyLoading();
	if ( isBytecodeEnhanced && !collection.wasInitialized() ) {
		// skip it
		LOG.debugf(
				"Skipping uninitialized bytecode-lazy collection: %s",
				MessageHelper.collectionInfoString( persister, collection, ce.getCurrentKey(), session )
		);
		ce.setReached( true );
		ce.setProcessed( true );
	}
	else {
		// The CollectionEntry.isReached() stuff is just to detect any silly users
		// who set up circular or shared references between/to collections.
		if ( ce.isReached() ) {
			// We've been here before
			throw new HibernateException(
					"Found shared references to a collection: " + type.getRole()
			);
		}
		ce.setReached( true );

		if ( LOG.isDebugEnabled() ) {
			if ( collection.wasInitialized() ) {
				LOG.debugf(
						"Collection found: %s, was: %s (initialized)",
						MessageHelper.collectionInfoString(
								persister,
								collection,
								ce.getCurrentKey(),
								session
						),
						MessageHelper.collectionInfoString(
								ce.getLoadedPersister(),
								collection,
								ce.getLoadedKey(),
								session
						)
				);
			}
			else {
				LOG.debugf(
						"Collection found: %s, was: %s (uninitialized)",
						MessageHelper.collectionInfoString(
								persister,
								collection,
								ce.getCurrentKey(),
								session
						),
						MessageHelper.collectionInfoString(
								ce.getLoadedPersister(),
								collection,
								ce.getLoadedKey(),
								session
						)
				);
			}
		}

		prepareCollectionForUpdate( collection, ce, factory );
	}
}
 
源代码11 项目: lams   文件: CollectionLoadContext.java
/**
 * Retrieve the collection that is being loaded as part of processing this
 * result set.
 * <p/>
 * Basically, there are two valid return values from this method:<ul>
 * <li>an instance of {@link org.hibernate.collection.spi.PersistentCollection} which indicates to
 * continue loading the result set row data into that returned collection
 * instance; this may be either an instance already associated and in the
 * midst of being loaded, or a newly instantiated instance as a matching
 * associated collection was not found.</li>
 * <li><i>null</i> indicates to ignore the corresponding result set row
 * data relating to the requested collection; this indicates that either
 * the collection was found to already be associated with the persistence
 * context in a fully loaded state, or it was found in a loading state
 * associated with another result set processing context.</li>
 * </ul>
 *
 * @param persister The persister for the collection being requested.
 * @param key The key of the collection being requested.
 *
 * @return The loading collection (see discussion above).
 */
public PersistentCollection getLoadingCollection(final CollectionPersister persister, final Serializable key) {
	final EntityMode em = persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode();
	final CollectionKey collectionKey = new CollectionKey( persister, key, em );
	if ( LOG.isTraceEnabled() ) {
		LOG.tracev( "Starting attempt to find loading collection [{0}]",
				MessageHelper.collectionInfoString( persister.getRole(), key ) );
	}
	final LoadingCollectionEntry loadingCollectionEntry = loadContexts.locateLoadingCollectionEntry( collectionKey );
	if ( loadingCollectionEntry == null ) {
		// look for existing collection as part of the persistence context
		PersistentCollection collection = loadContexts.getPersistenceContext().getCollection( collectionKey );
		if ( collection != null ) {
			if ( collection.wasInitialized() ) {
				LOG.trace( "Collection already initialized; ignoring" );
				// ignore this row of results! Note the early exit
				return null;
			}
			LOG.trace( "Collection not yet initialized; initializing" );
		}
		else {
			final Object owner = loadContexts.getPersistenceContext().getCollectionOwner( key, persister );
			final boolean newlySavedEntity = owner != null
					&& loadContexts.getPersistenceContext().getEntry( owner ).getStatus() != Status.LOADING;
			if ( newlySavedEntity ) {
				// important, to account for newly saved entities in query
				// todo : some kind of check for new status...
				LOG.trace( "Owning entity already loaded; ignoring" );
				return null;
			}
			// create one
			LOG.tracev( "Instantiating new collection [key={0}, rs={1}]", key, resultSet );
			collection = persister.getCollectionType().instantiate(
					loadContexts.getPersistenceContext().getSession(), persister, key );
		}
		collection.beforeInitialize( persister, -1 );
		collection.beginRead();
		localLoadingCollectionKeys.add( collectionKey );
		loadContexts.registerLoadingCollectionXRef( collectionKey, new LoadingCollectionEntry( resultSet, persister, key, collection ) );
		return collection;
	}
	if ( loadingCollectionEntry.getResultSet() == resultSet ) {
		LOG.trace( "Found loading collection bound to current result set processing; reading row" );
		return loadingCollectionEntry.getCollection();
	}
	// ignore this row, the collection is in process of
	// being loaded somewhere further "up" the stack
	LOG.trace( "Collection is already being initialized; ignoring row" );
	return null;
}
 
/**
 * called by a collection that wants to initialize itself
 */
public void onInitializeCollection(InitializeCollectionEvent event) throws HibernateException {
	PersistentCollection collection = event.getCollection();
	SessionImplementor source = event.getSession();

	CollectionEntry ce = source.getPersistenceContext().getCollectionEntry( collection );
	if ( ce == null ) {
		throw new HibernateException( "collection was evicted" );
	}
	if ( !collection.wasInitialized() ) {
		final boolean traceEnabled = LOG.isTraceEnabled();
		if ( traceEnabled ) {
			LOG.tracev(
					"Initializing collection {0}",
					MessageHelper.collectionInfoString(
							ce.getLoadedPersister(),
							collection,
							ce.getLoadedKey(),
							source
					)
			);
			LOG.trace( "Checking second-level cache" );
		}

		final boolean foundInCache = initializeCollectionFromCache(
				ce.getLoadedKey(),
				ce.getLoadedPersister(),
				collection,
				source
		);

		if ( foundInCache ) {
			if ( traceEnabled ) {
				LOG.trace( "Collection initialized from cache" );
			}
		}
		else {
			if ( traceEnabled ) {
				LOG.trace( "Collection not cached" );
			}
			ce.getLoadedPersister().initialize( ce.getLoadedKey(), source );
			if ( traceEnabled ) {
				LOG.trace( "Collection initialized" );
			}

			if ( source.getFactory().getStatistics().isStatisticsEnabled() ) {
				source.getFactory().getStatistics().fetchCollection(
						ce.getLoadedPersister().getRole()
				);
			}
		}
	}
}
 
源代码13 项目: lams   文件: CollectionUpdateAction.java
@Override
public void execute() throws HibernateException {
	final Serializable id = getKey();
	final SharedSessionContractImplementor session = getSession();
	final CollectionPersister persister = getPersister();
	final PersistentCollection collection = getCollection();
	final boolean affectedByFilters = persister.isAffectedByEnabledFilters( session );

	preUpdate();

	if ( !collection.wasInitialized() ) {
		if ( !collection.hasQueuedOperations() ) {
			throw new AssertionFailure( "no queued adds" );
		}
		//do nothing - we only need to notify the cache... 
	}
	else if ( !affectedByFilters && collection.empty() ) {
		if ( !emptySnapshot ) {
			persister.remove( id, session );
		}
	}
	else if ( collection.needsRecreate( persister ) ) {
		if ( affectedByFilters ) {
			throw new HibernateException(
					"cannot recreate collection while filter is enabled: " +
							MessageHelper.collectionInfoString( persister, collection, id, session )
			);
		}
		if ( !emptySnapshot ) {
			persister.remove( id, session );
		}
		persister.recreate( collection, id, session );
	}
	else {
		persister.deleteRows( collection, id, session );
		persister.updateRows( collection, id, session );
		persister.insertRows( collection, id, session );
	}

	getSession().getPersistenceContext().getCollectionEntry( collection ).afterAction( collection );
	evict();
	postUpdate();

	if ( getSession().getFactory().getStatistics().isStatisticsEnabled() ) {
		getSession().getFactory().getStatistics().updateCollection( getPersister().getRole() );
	}
}