org.hibernate.engine.SessionImplementor#getPersistenceContext ( )源码实例Demo

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

源代码1 项目: cacheonix-core   文件: Loader.java
/**
 * Execute an SQL query and attempt to instantiate instances of the class mapped by the given
 * persister from each row of the <tt>ResultSet</tt>. If an object is supplied, will attempt to
 * initialize that object. If a collection is supplied, attempt to initialize that collection.
 */
private List doQueryAndInitializeNonLazyCollections(final SessionImplementor session,
													final QueryParameters queryParameters,
													final boolean returnProxies) 
	throws HibernateException, SQLException {

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	persistenceContext.beforeLoad();
	List result;
	try {
		result = doQuery( session, queryParameters, returnProxies );
	}
	finally {
		persistenceContext.afterLoad();
	}
	persistenceContext.initializeNonLazyCollections();
	return result;
}
 
private CollectionInitializer getSubselectInitializer(Serializable key, SessionImplementor session) {

		if ( !isSubselectLoadable() ) {
			return null;
		}
		
		final PersistenceContext persistenceContext = session.getPersistenceContext();
		
		SubselectFetch subselect = persistenceContext.getBatchFetchQueue()
			.getSubselect( new EntityKey( key, getOwnerEntityPersister(), session.getEntityMode() ) );
		
		if (subselect == null) {
			return null;
		}
		else {
			
			// Take care of any entities that might have
			// been evicted!	
			Iterator iter = subselect.getResult().iterator();
			while ( iter.hasNext() ) {
				if ( !persistenceContext.containsEntity( (EntityKey) iter.next() ) ) {
					iter.remove();
				}
			}	
			
			// Run a subquery loader
			return createSubselectInitializer( subselect, session );
		}
	}
 
源代码3 项目: cacheonix-core   文件: WrapVisitor.java
final Object processArrayOrNewCollection(Object collection, CollectionType collectionType)
throws HibernateException {

	final SessionImplementor session = getSession();

	if (collection==null) {
		//do nothing
		return null;
	}
	else {
		CollectionPersister persister = session.getFactory().getCollectionPersister( collectionType.getRole() );

		final PersistenceContext persistenceContext = session.getPersistenceContext();
		//TODO: move into collection type, so we can use polymorphism!
		if ( collectionType.hasHolder( session.getEntityMode() ) ) {
			
			if (collection==CollectionType.UNFETCHED_COLLECTION) return null;

			PersistentCollection ah = persistenceContext.getCollectionHolder(collection);
			if (ah==null) {
				ah = collectionType.wrap(session, collection);
				persistenceContext.addNewCollection( persister, ah );
				persistenceContext.addCollectionHolder(ah);
			}
			return null;
		}
		else {

			PersistentCollection persistentCollection = collectionType.wrap(session, collection);
			persistenceContext.addNewCollection( persister, persistentCollection );

			if ( log.isTraceEnabled() ) log.trace( "Wrapped collection in role: " + collectionType.getRole() );

			return persistentCollection; //Force a substitution!

		}

	}

}
 
/**
 * 1. Recreate the collection key -> collection map
 * 2. rebuild the collection entries
 * 3. call Interceptor.postFlush()
 */
protected void postFlush(SessionImplementor session) throws HibernateException {

	log.trace( "post flush" );

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	persistenceContext.getCollectionsByKey().clear();
	persistenceContext.getBatchFetchQueue()
			.clearSubselects(); //the database has changed now, so the subselect results need to be invalidated

	Iterator iter = persistenceContext.getCollectionEntries().entrySet().iterator();
	while ( iter.hasNext() ) {
		Map.Entry me = (Map.Entry) iter.next();
		CollectionEntry collectionEntry = (CollectionEntry) me.getValue();
		PersistentCollection persistentCollection = (PersistentCollection) me.getKey();
		collectionEntry.postFlush(persistentCollection);
		if ( collectionEntry.getLoadedPersister() == null ) {
			//if the collection is dereferenced, remove from the session cache
			//iter.remove(); //does not work, since the entrySet is not backed by the set
			persistenceContext.getCollectionEntries()
					.remove(persistentCollection);
		}
		else {
			//otherwise recreate the mapping between the collection and its key
			CollectionKey collectionKey = new CollectionKey( 
					collectionEntry.getLoadedPersister(), 
					collectionEntry.getLoadedKey(), 
					session.getEntityMode() 
				);
			persistenceContext.getCollectionsByKey()
					.put(collectionKey, persistentCollection);
		}
	}
	
	session.getInterceptor().postFlush( new LazyIterator( persistenceContext.getEntitiesByKey() ) );

}
 
源代码5 项目: cacheonix-core   文件: CollectionType.java
/**
 * instantiate a collection wrapper (called when loading an object)
 *
 * @param key The collection owner key
 * @param session The session from which the request is originating.
 * @param owner The collection owner
 * @return The collection
 */
public Object getCollection(Serializable key, SessionImplementor session, Object owner) {

	CollectionPersister persister = getPersister( session );
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	final EntityMode entityMode = session.getEntityMode();

	if (entityMode==EntityMode.DOM4J && !isEmbeddedInXML) {
		return UNFETCHED_COLLECTION;
	}

	// check if collection is currently being loaded
	PersistentCollection collection = persistenceContext.getLoadContexts().locateLoadingCollection( persister, key );
	if ( collection == null ) {
		// check if it is already completely loaded, but unowned
		collection = persistenceContext.useUnownedCollection( new CollectionKey(persister, key, entityMode) );
		if ( collection == null ) {
			// create a new collection wrapper, to be initialized later
			collection = instantiate( session, persister, key );
			collection.setOwner( owner );

			persistenceContext.addUninitializedCollection( persister, collection, key );

			// some collections are not lazy:
			if ( initializeImmediately( entityMode ) ) {
				session.initializeCollection( collection, false );
			}
			else if ( !persister.isLazy() ) {
				persistenceContext.addNonLazyCollection( collection );
			}

			if ( hasHolder( entityMode ) ) {
				session.getPersistenceContext().addCollectionHolder( collection );
			}
		}
	}
	collection.setOwner( owner );
	return collection.getValue();
}
 
源代码6 项目: cacheonix-core   文件: EntityType.java
/**
 * Load an instance by a unique key that is not the primary key.
 *
 * @param entityName The name of the entity to load
 * @param uniqueKeyPropertyName The name of the property defining the uniqie key.
 * @param key The unique key property value.
 * @param session The originating session.
 * @return The loaded entity
 * @throws HibernateException generally indicates problems performing the load.
 */
public Object loadByUniqueKey(
		String entityName, 
		String uniqueKeyPropertyName, 
		Object key, 
		SessionImplementor session) throws HibernateException {
	final SessionFactoryImplementor factory = session.getFactory();
	UniqueKeyLoadable persister = ( UniqueKeyLoadable ) factory.getEntityPersister( entityName );

	//TODO: implement caching?! proxies?!

	EntityUniqueKey euk = new EntityUniqueKey(
			entityName, 
			uniqueKeyPropertyName, 
			key, 
			getIdentifierOrUniqueKeyType( factory ),
			session.getEntityMode(), 
			session.getFactory()
	);

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	Object result = persistenceContext.getEntity( euk );
	if ( result == null ) {
		result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session );
	}
	return result == null ? null : persistenceContext.proxyFor( result );
}
 
源代码7 项目: cacheonix-core   文件: Loader.java
/**
 * For missing objects associated by one-to-one with another object in the
 * result set, register the fact that the the object is missing with the
 * session.
 */
private void registerNonExists(
        final EntityKey[] keys,
        final Loadable[] persisters,
        final SessionImplementor session) {
	
	final int[] owners = getOwners();
	if ( owners != null ) {
		
		EntityType[] ownerAssociationTypes = getOwnerAssociationTypes();
		for ( int i = 0; i < keys.length; i++ ) {
			
			int owner = owners[i];
			if ( owner > -1 ) {
				EntityKey ownerKey = keys[owner];
				if ( keys[i] == null && ownerKey != null ) {
					
					final PersistenceContext persistenceContext = session.getPersistenceContext();
					
					/*final boolean isPrimaryKey;
					final boolean isSpecialOneToOne;
					if ( ownerAssociationTypes == null || ownerAssociationTypes[i] == null ) {
						isPrimaryKey = true;
						isSpecialOneToOne = false;
					}
					else {
						isPrimaryKey = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName()==null;
						isSpecialOneToOne = ownerAssociationTypes[i].getLHSPropertyName()!=null;
					}*/
					
					//TODO: can we *always* use the "null property" approach for everything?
					/*if ( isPrimaryKey && !isSpecialOneToOne ) {
						persistenceContext.addNonExistantEntityKey( 
								new EntityKey( ownerKey.getIdentifier(), persisters[i], session.getEntityMode() ) 
						);
					}
					else if ( isSpecialOneToOne ) {*/
					boolean isOneToOneAssociation = ownerAssociationTypes!=null && 
							ownerAssociationTypes[i]!=null && 
							ownerAssociationTypes[i].isOneToOne();
					if ( isOneToOneAssociation ) {
						persistenceContext.addNullProperty( ownerKey, 
								ownerAssociationTypes[i].getPropertyName() );
					}
					/*}
					else {
						persistenceContext.addNonExistantEntityUniqueKey( new EntityUniqueKey( 
								persisters[i].getEntityName(),
								ownerAssociationTypes[i].getRHSUniqueKeyPropertyName(),
								ownerKey.getIdentifier(),
								persisters[owner].getIdentifierType(),
								session.getEntityMode()
						) );
					}*/
				}
			}
		}
	}
}
 
源代码8 项目: cacheonix-core   文件: Loader.java
/**
 * Read one collection element from the current row of the JDBC result set
 */
private void readCollectionElement(
        final Object optionalOwner,
        final Serializable optionalKey,
        final CollectionPersister persister,
        final CollectionAliases descriptor,
        final ResultSet rs,
        final SessionImplementor session) 
throws HibernateException, SQLException {

	final PersistenceContext persistenceContext = session.getPersistenceContext();

	final Serializable collectionRowKey = (Serializable) persister.readKey( 
			rs, 
			descriptor.getSuffixedKeyAliases(), 
			session 
		);
	
	if ( collectionRowKey != null ) {
		// we found a collection element in the result set

		if ( log.isDebugEnabled() ) {
			log.debug( 
					"found row of collection: " +
					MessageHelper.collectionInfoString( persister, collectionRowKey, getFactory() ) 
				);
		}

		Object owner = optionalOwner;
		if ( owner == null ) {
			owner = persistenceContext.getCollectionOwner( collectionRowKey, persister );
			if ( owner == null ) {
				//TODO: This is assertion is disabled because there is a bug that means the
				//	  original owner of a transient, uninitialized collection is not known
				//	  if the collection is re-referenced by a different object associated
				//	  with the current Session
				//throw new AssertionFailure("bug loading unowned collection");
			}
		}

		PersistentCollection rowCollection = persistenceContext.getLoadContexts()
				.getCollectionLoadContext( rs )
				.getLoadingCollection( persister, collectionRowKey );

		if ( rowCollection != null ) {
			rowCollection.readFrom( rs, persister, descriptor, owner );
		}

	}
	else if ( optionalKey != null ) {
		// we did not find a collection element in the result set, so we
		// ensure that a collection is created with the owner's identifier,
		// since what we have is an empty collection

		if ( log.isDebugEnabled() ) {
			log.debug( 
					"result set contains (possibly empty) collection: " +
					MessageHelper.collectionInfoString( persister, optionalKey, getFactory() ) 
				);
		}

		persistenceContext.getLoadContexts()
				.getCollectionLoadContext( rs )
				.getLoadingCollection( persister, optionalKey ); // handle empty collection
	}

	// else no collection element, but also no owner

}
 
/**
 * 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;
		}
		
	}
}
 
源代码10 项目: cacheonix-core   文件: EntityDeleteAction.java
public void execute() throws HibernateException {
	Serializable id = getId();
	EntityPersister persister = getPersister();
	SessionImplementor session = getSession();
	Object instance = getInstance();

	boolean veto = preDelete();

	Object version = this.version;
	if ( persister.isVersionPropertyGenerated() ) {
		// we need to grab the version value from the entity, otherwise
		// we have issues with generated-version entities that may have
		// multiple actions queued during the same flush
		version = persister.getVersion( instance, session.getEntityMode() );
	}

	final CacheKey ck;
	if ( persister.hasCache() ) {
		ck = new CacheKey( 
				id, 
				persister.getIdentifierType(), 
				persister.getRootEntityName(), 
				session.getEntityMode(), 
				session.getFactory() 
			);
		lock = persister.getCache().lock(ck, version);
	}
	else {
		ck = null;
	}

	if ( !isCascadeDeleteEnabled && !veto ) {
		persister.delete( id, version, instance, session );
	}
	
	//postDelete:
	// After actually deleting a row, record the fact that the instance no longer 
	// exists on the database (needed for identity-column key generation), and
	// remove it from the session cache
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	EntityEntry entry = persistenceContext.removeEntry( instance );
	if ( entry == null ) {
		throw new AssertionFailure( "possible nonthreadsafe access to session" );
	}
	entry.postDelete();

	EntityKey key = new EntityKey( entry.getId(), entry.getPersister(), session.getEntityMode() );
	persistenceContext.removeEntity(key);
	persistenceContext.removeProxy(key);
	
	if ( persister.hasCache() ) persister.getCache().evict(ck);

	postDelete();

	if ( getSession().getFactory().getStatistics().isStatisticsEnabled() && !veto ) {
		getSession().getFactory().getStatisticsImplementor()
				.deleteEntity( getPersister().getEntityName() );
	}
}
 
源代码11 项目: webdsl   文件: BatchingCollectionInitializer.java
/**
 * 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
}