Java Code Examples for org.hibernate.collection.PersistentCollection#wasInitialized()

The following examples show how to use org.hibernate.collection.PersistentCollection#wasInitialized() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Cascade.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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() ) {
		CollectionEntry ce = eventSource.getPersistenceContext().getCollectionEntry(pc);
		orphans = ce==null ?
				CollectionHelper.EMPTY_COLLECTION :
				ce.getOrphans(entityName, pc);
	}
	else {
		orphans = pc.getQueuedOrphans(entityName);
	}

	final Iterator orphanIter = orphans.iterator();
	while ( orphanIter.hasNext() ) {
		Object orphan = orphanIter.next();
		if (orphan!=null) {
			if ( log.isTraceEnabled() ) {
				log.trace("deleting orphaned entity instance: " + entityName);
			}
			eventSource.delete( entityName, orphan, false, null );
		}
	}
}
 
Example 2
Source File: CollectionEntry.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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();
	}
	
}
 
Example 3
Source File: CollectionEntry.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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();
}
 
Example 4
Source File: CollectionEntry.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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() );
}
 
Example 5
Source File: OnReplicateVisitor.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
Object processCollection(Object collection, CollectionType type)
		throws HibernateException {

	if ( collection == CollectionType.UNFETCHED_COLLECTION ) {
		return null;
	}

	EventSource session = getSession();
	CollectionPersister persister = session.getFactory().getCollectionPersister( type.getRole() );

	if ( isUpdate ) {
		removeCollection( persister, extractCollectionKeyFromOwner( persister ), session );
	}
	if ( collection != null && ( collection instanceof PersistentCollection ) ) {
		PersistentCollection wrapper = ( PersistentCollection ) collection;
		wrapper.setCurrentSession( 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;

}
 
Example 6
Source File: BatchFetchQueue.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * 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,
		final EntityMode entityMode) {
	Serializable[] keys = new Serializable[batchSize];
	keys[0] = id;
	int i = 1;
	//int count = 0;
	int end = -1;
	boolean checkForEnd = false;
	// this only works because collection entries are kept in a sequenced
	// map by persistence context (maybe we should do like entities and
	// keep a separate sequences set...)
	Iterator iter = context.getCollectionEntries().entrySet().iterator(); //TODO: calling entrySet on an IdentityMap is SLOW!!
	while ( iter.hasNext() ) {
		Map.Entry me = (Map.Entry) iter.next();

		CollectionEntry ce = (CollectionEntry) me.getValue();
		PersistentCollection collection = (PersistentCollection) me.getKey();
		if ( !collection.wasInitialized() && ce.getLoadedPersister() == collectionPersister ) {

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

			//if ( end == -1 && count > batchSize*10 ) return keys; //try out ten batches, max

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

			if ( isEqual ) {
				end = i;
				//checkForEnd = false;
			}
			else if ( !isCached( ce.getLoadedKey(), collectionPersister, entityMode ) ) {
				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
}
 
Example 7
Source File: CollectionLoadContext.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * 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 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 = loadContexts.getPersistenceContext().getSession().getEntityMode();
	final CollectionKey collectionKey = new CollectionKey( persister, key, em );
	if ( log.isTraceEnabled() ) {
		log.trace( "starting attempt to find loading collection [" + 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" );
				return null; // ignore this row of results! Note the early exit
			}
			else {
				// initialize this collection
				log.trace( "collection not yet initialized; initializing" );
			}
		}
		else {
			Object owner = loadContexts.getPersistenceContext().getCollectionOwner( key, persister );
			final boolean newlySavedEntity = owner != null
					&& loadContexts.getPersistenceContext().getEntry( owner ).getStatus() != Status.LOADING
					&& em != EntityMode.DOM4J;
			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;
			}
			else {
				// create one
				if ( log.isTraceEnabled() ) {
					log.trace( "instantiating new collection [key=" + key + ", rs=" + 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;
	}
	else {
		if ( loadingCollectionEntry.getResultSet() == resultSet ) {
			log.trace( "found loading collection bound to current result set processing; reading row" );
			return loadingCollectionEntry.getCollection();
		}
		else {
			// 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;
		}
	}
}
 
Example 8
Source File: DefaultInitializeCollectionEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * 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() ) {
		if ( log.isTraceEnabled() ) {
			log.trace(
					"initializing collection " +
					MessageHelper.collectionInfoString( ce.getLoadedPersister(), ce.getLoadedKey(), source.getFactory() )
				);
		}

		log.trace("checking second-level cache");
		final boolean foundInCache = initializeCollectionFromCache(
				ce.getLoadedKey(),
				ce.getLoadedPersister(),
				collection,
				source
			);

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

			if ( source.getFactory().getStatistics().isStatisticsEnabled() ) {
				source.getFactory().getStatisticsImplementor().fetchCollection( 
						ce.getLoadedPersister().getRole() 
					);
			}
		}
	}
}
 
Example 9
Source File: CollectionUpdateAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void execute() throws HibernateException {
	final Serializable id = getKey();
	final SessionImplementor session = getSession();
	final CollectionPersister persister = getPersister();
	final PersistentCollection collection = getCollection();
	boolean affectedByFilters = persister.isAffectedByEnabledFilters(session);

	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, id, persister.getFactory() )
			);
		}
		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();

	if ( getSession().getFactory().getStatistics().isStatisticsEnabled() ) {
		getSession().getFactory().getStatisticsImplementor().
				updateCollection( getPersister().getRole() );
	}
}
 
Example 10
Source File: BatchingCollectionInitializer.java    From webdsl with Apache License 2.0 4 votes vote down vote up
/**
 * Get a batch of uninitialized collection keys for a given role
 * Original implementation in org.hibernate.engine.BatchFetchQueue
 * This implementation maintains the sequence of the collection entries 
 *
 * @param session The originating session
 * @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 static Serializable[] getCollectionBatch(
	    final SessionImplementor session,
		final CollectionPersister collectionPersister,
		final Serializable id,
		final int batchSize,
		final EntityMode entityMode) {
	Serializable[] keys = new Serializable[batchSize];
	keys[0] = id;
	int i = 1;
	//int count = 0;
	int end = -1;
	boolean checkForEnd = false;
	// this only works because collection entries are kept in a sequenced
	// map by persistence context (maybe we should do like entities and
	// keep a separate sequences set...)
	PersistenceContext context = session.getPersistenceContext();
	Iterator iter = ((IdentityMap)context.getCollectionEntries()).entryList().iterator(); // Note the entryList() instead of the entrySet()
	while ( iter.hasNext() ) {
		Map.Entry me = (Map.Entry) iter.next();

		CollectionEntry ce = (CollectionEntry) me.getValue();
		PersistentCollection collection = (PersistentCollection) me.getKey();
		if ( !collection.wasInitialized() && ce.getLoadedPersister() == collectionPersister ) {

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

			//if ( end == -1 && count > batchSize*10 ) return keys; //try out ten batches, max

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

			if ( isEqual ) {
				end = i;
				//checkForEnd = false;
			}
			else if ( !isCached( context, ce.getLoadedKey(), collectionPersister, entityMode ) ) {
				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
}