Java Code Examples for org.hibernate.engine.spi.SharedSessionContractImplementor#getPersistenceContext()

The following examples show how to use org.hibernate.engine.spi.SharedSessionContractImplementor#getPersistenceContext() . 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: TwoPhaseLoad.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * PostLoad cannot occur during initializeEntity, as that call occurs *before*
 * the Set collections are added to the persistence context by Loader.
 * Without the split, LazyInitializationExceptions can occur in the Entity's
 * postLoad if it acts upon the collection.
 *
 * HHH-6043
 *
 * @param entity The entity
 * @param session The Session
 * @param postLoadEvent The (re-used) post-load event
 */
public static void postLoad(
		final Object entity,
		final SharedSessionContractImplementor session,
		final PostLoadEvent postLoadEvent) {

	if ( session.isEventSource() ) {
		final PersistenceContext persistenceContext
				= session.getPersistenceContext();
		final EntityEntry entityEntry = persistenceContext.getEntry( entity );

		postLoadEvent.setEntity( entity ).setId( entityEntry.getId() ).setPersister( entityEntry.getPersister() );

		final EventListenerGroup<PostLoadEventListener> listenerGroup = session.getFactory()
						.getServiceRegistry()
						.getService( EventListenerRegistry.class )
						.getEventListenerGroup( EventType.POST_LOAD );
		for ( PostLoadEventListener listener : listenerGroup.listeners() ) {
			listener.onPostLoad( postLoadEvent );
		}
	}
}
 
Example 2
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public List doQueryAndInitializeNonLazyCollections(
		final SharedSessionContractImplementor session,
		final QueryParameters queryParameters,
		final boolean returnProxies,
		final ResultTransformer forcedResultTransformer)
		throws HibernateException, SQLException {
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	boolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();
	if ( queryParameters.isReadOnlyInitialized() ) {
		// The read-only/modifiable mode for the query was explicitly set.
		// Temporarily set the default read-only/modifiable setting to the query's setting.
		persistenceContext.setDefaultReadOnly( queryParameters.isReadOnly() );
	}
	else {
		// The read-only/modifiable setting for the query was not initialized.
		// Use the default read-only/modifiable from the persistence context instead.
		queryParameters.setReadOnly( persistenceContext.isDefaultReadOnly() );
	}
	persistenceContext.beforeLoad();
	List result;
	try {
		try {
			result = doQuery( session, queryParameters, returnProxies, forcedResultTransformer );
		}
		finally {
			persistenceContext.afterLoad();
		}
		persistenceContext.initializeNonLazyCollections();
	}
	finally {
		// Restore the original default
		persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );
	}
	return result;
}
 
Example 3
Source File: EntityType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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,
		SharedSessionContractImplementor session) throws HibernateException {
	final SessionFactoryImplementor factory = session.getFactory();
	UniqueKeyLoadable persister = (UniqueKeyLoadable) factory.getMetamodel().entityPersister( entityName );

	//TODO: implement 2nd level caching?! natural id caching ?! proxies?!

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

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	Object result = persistenceContext.getEntity( euk );
	if ( result == null ) {
		result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session );
		
		// If the entity was not in the Persistence Context, but was found now,
		// add it to the Persistence Context
		if (result != null) {
			persistenceContext.addEntity(euk, result);
		}
	}

	return result == null ? null : persistenceContext.proxyFor( result );
}
 
Example 4
Source File: AbstractEntityTuplizer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setIdentifier(Object entity, Serializable id, EntityMode entityMode, SharedSessionContractImplementor session) {
	final Object[] extractedValues = mappedIdentifierType.getPropertyValues( id, entityMode );
	final Object[] injectionValues = new Object[extractedValues.length];
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	for ( int i = 0; i < virtualIdComponent.getSubtypes().length; i++ ) {
		final Type virtualPropertyType = virtualIdComponent.getSubtypes()[i];
		final Type idClassPropertyType = mappedIdentifierType.getSubtypes()[i];
		if ( virtualPropertyType.isEntityType() && !idClassPropertyType.isEntityType() ) {
			if ( session == null ) {
				throw new AssertionError(
						"Deprecated version of getIdentifier (no session) was used but session was required"
				);
			}
			final String associatedEntityName = ( (EntityType) virtualPropertyType ).getAssociatedEntityName();
			final EntityKey entityKey = session.generateEntityKey(
					(Serializable) extractedValues[i],
					sessionFactory.getMetamodel().entityPersister( associatedEntityName )
			);
			// it is conceivable there is a proxy, so check that first
			Object association = persistenceContext.getProxy( entityKey );
			if ( association == null ) {
				// otherwise look for an initialized version
				association = persistenceContext.getEntity( entityKey );
				if ( association == null ) {
					// get the association out of the entity itself
					association = sessionFactory.getMetamodel().entityPersister( entityName ).getPropertyValue(
							entity,
							virtualIdComponent.getPropertyNames()[i]
					);
				}
			}
			injectionValues[i] = association;
		}
		else {
			injectionValues[i] = extractedValues[i];
		}
	}
	virtualIdComponent.setPropertyValues( entity, injectionValues, entityMode );
}
 
Example 5
Source File: AbstractCollectionPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private CollectionInitializer getSubselectInitializer(Serializable key, SharedSessionContractImplementor session) {

		if ( !isSubselectLoadable() ) {
			return null;
		}

		final PersistenceContext persistenceContext = session.getPersistenceContext();

		SubselectFetch subselect = persistenceContext.getBatchFetchQueue()
				.getSubselect( session.generateEntityKey( key, getOwnerEntityPersister() ) );

		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 );
		}
	}
 
Example 6
Source File: DynamicBatchingCollectionInitializerBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public final void doBatchedCollectionLoad(
		final SharedSessionContractImplementor session,
		final Serializable[] ids,
		final Type type) throws HibernateException {

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf(
				"Batch loading collection: %s",
				MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() )
		);
	}

	final Type[] idTypes = new Type[ids.length];
	Arrays.fill( idTypes, type );
	final QueryParameters queryParameters = new QueryParameters( idTypes, ids, ids );

	final String sql = StringHelper.expandBatchIdPlaceholder(
			sqlTemplate,
			ids,
			alias,
			collectionPersister().getKeyColumnNames(),
			session.getJdbcServices().getJdbcEnvironment().getDialect()
	);

	try {
		final PersistenceContext persistenceContext = session.getPersistenceContext();
		boolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();
		if ( queryParameters.isReadOnlyInitialized() ) {
			// The read-only/modifiable mode for the query was explicitly set.
			// Temporarily set the default read-only/modifiable setting to the query's setting.
			persistenceContext.setDefaultReadOnly( queryParameters.isReadOnly() );
		}
		else {
			// The read-only/modifiable setting for the query was not initialized.
			// Use the default read-only/modifiable from the persistence context instead.
			queryParameters.setReadOnly( persistenceContext.isDefaultReadOnly() );
		}
		persistenceContext.beforeLoad();
		try {
			try {
				doTheLoad( sql, queryParameters, session );
			}
			finally {
				persistenceContext.afterLoad();
			}
			persistenceContext.initializeNonLazyCollections();
		}
		finally {
			// Restore the original default
			persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );
		}
	}
	catch ( SQLException e ) {
		throw session.getJdbcServices().getSqlExceptionHelper().convert(
				e,
				"could not initialize a collection batch: " +
						MessageHelper.collectionInfoString( collectionPersister(), ids, getFactory() ),
				sql
		);
	}

	LOG.debug( "Done batch load" );

}
 
Example 7
Source File: AbstractLoadPlanBasedLoader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected List executeLoad(
		SharedSessionContractImplementor session,
		QueryParameters queryParameters,
		LoadQueryDetails loadQueryDetails,
		boolean returnProxies,
		ResultTransformer forcedResultTransformer,
		List<AfterLoadAction> afterLoadActions) throws SQLException {
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	final boolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();
	if ( queryParameters.isReadOnlyInitialized() ) {
		// The read-only/modifiable mode for the query was explicitly set.
		// Temporarily set the default read-only/modifiable setting to the query's setting.
		persistenceContext.setDefaultReadOnly( queryParameters.isReadOnly() );
	}
	else {
		// The read-only/modifiable setting for the query was not initialized.
		// Use the default read-only/modifiable from the persistence context instead.
		queryParameters.setReadOnly( persistenceContext.isDefaultReadOnly() );
	}
	persistenceContext.beforeLoad();
	try {
		List results = null;
		final String sql = loadQueryDetails.getSqlStatement();
		SqlStatementWrapper wrapper = null;
		try {
			wrapper = executeQueryStatement( sql, queryParameters, false, afterLoadActions, session );
			results = loadQueryDetails.getResultSetProcessor().extractResults(
					wrapper.getResultSet(),
					session,
					queryParameters,
					new NamedParameterContext() {
						@Override
						public int[] getNamedParameterLocations(String name) {
							return AbstractLoadPlanBasedLoader.this.getNamedParameterLocs( name );
						}
					},
					returnProxies,
					queryParameters.isReadOnly(),
					forcedResultTransformer,
					afterLoadActions
			);
		}
		finally {
			if ( wrapper != null ) {
				session.getJdbcCoordinator().getResourceRegistry().release(
						wrapper.getResultSet(),
						wrapper.getStatement()
				);
				session.getJdbcCoordinator().getResourceRegistry().release( wrapper.getStatement() );
				session.getJdbcCoordinator().afterStatementExecution();
			}
			persistenceContext.afterLoad();
		}
		persistenceContext.initializeNonLazyCollections();
		return results;
	}
	finally {
		// Restore the original default
		persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );
	}
}
 
Example 8
Source File: Loader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private List getResultFromQueryCache(
		final SharedSessionContractImplementor session,
		final QueryParameters queryParameters,
		final Set<Serializable> querySpaces,
		final Type[] resultTypes,
		final QueryResultsCache queryCache,
		final QueryKey key) {
	List result = null;

	if ( session.getCacheMode().isGetEnabled() ) {
		boolean isImmutableNaturalKeyLookup =
				queryParameters.isNaturalKeyLookup() &&
						resultTypes.length == 1 &&
						resultTypes[0].isEntityType() &&
						getEntityPersister( EntityType.class.cast( resultTypes[0] ) )
								.getEntityMetamodel()
								.hasImmutableNaturalId();

		final PersistenceContext persistenceContext = session.getPersistenceContext();
		boolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();
		if ( queryParameters.isReadOnlyInitialized() ) {
			// The read-only/modifiable mode for the query was explicitly set.
			// Temporarily set the default read-only/modifiable setting to the query's setting.
			persistenceContext.setDefaultReadOnly( queryParameters.isReadOnly() );
		}
		else {
			// The read-only/modifiable setting for the query was not initialized.
			// Use the default read-only/modifiable from the persistence context instead.
			queryParameters.setReadOnly( persistenceContext.isDefaultReadOnly() );
		}
		try {
			result = queryCache.get(
					key,
					querySpaces,
					key.getResultTransformer().getCachedResultTypes( resultTypes ),
					session
			);
		}
		finally {
			persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );
		}

		if ( factory.getStatistics().isStatisticsEnabled() ) {
			if ( result == null ) {
				factory.getStatistics().queryCacheMiss( getQueryIdentifier(), queryCache.getRegion().getName() );
			}
			else {
				factory.getStatistics().queryCacheHit( getQueryIdentifier(), queryCache.getRegion().getName() );
			}
		}
	}

	return result;
}
 
Example 9
Source File: Loader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 SharedSessionContractImplementor 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.debugf(
					"Found row of collection: %s",
					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.debugf(
					"Result set contains (possibly empty) collection: %s",
					MessageHelper.collectionInfoString( persister, optionalKey, getFactory() )
			);
		}

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

	}

	// else no collection element, but also no owner

}
 
Example 10
Source File: Loader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 SharedSessionContractImplementor 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()
						) );
					}*/
				}
			}
		}
	}
}
 
Example 11
Source File: EntityDeleteAction.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void execute() throws HibernateException {
	final Serializable id = getId();
	final EntityPersister persister = getPersister();
	final SharedSessionContractImplementor session = getSession();
	final Object instance = getInstance();

	final 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 );
	}

	final Object ck;
	if ( persister.canWriteToCache() ) {
		final EntityDataAccess cache = persister.getCacheAccessStrategy();
		ck = cache.generateCacheKey( id, persister, session.getFactory(), session.getTenantIdentifier() );
		lock = cache.lockItem( session, 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();
	final EntityEntry entry = persistenceContext.removeEntry( instance );
	if ( entry == null ) {
		throw new AssertionFailure( "possible nonthreadsafe access to session" );
	}
	entry.postDelete();

	persistenceContext.removeEntity( entry.getEntityKey() );
	persistenceContext.removeProxy( entry.getEntityKey() );
	
	if ( persister.canWriteToCache() ) {
		persister.getCacheAccessStrategy().remove( session, ck);
	}

	persistenceContext.getNaturalIdHelper().removeSharedNaturalIdCrossReference( persister, id, naturalIdValues );

	postDelete();

	if ( getSession().getFactory().getStatistics().isStatisticsEnabled() && !veto ) {
		getSession().getFactory().getStatistics().deleteEntity( getPersister().getEntityName() );
	}
}
 
Example 12
Source File: EntityInsertAction.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void execute() throws HibernateException {
	nullifyTransientReferencesIfNotAlready();

	final EntityPersister persister = getPersister();
	final SharedSessionContractImplementor session = getSession();
	final Object instance = getInstance();
	final Serializable id = getId();

	final 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, getState(), instance, session );
		PersistenceContext persistenceContext = session.getPersistenceContext();
		final EntityEntry entry = persistenceContext.getEntry( instance );
		if ( entry == null ) {
			throw new AssertionFailure( "possible non-threadsafe access to session" );
		}
		
		entry.postInsert( getState() );

		if ( persister.hasInsertGeneratedProperties() ) {
			persister.processInsertGeneratedProperties( id, instance, getState(), session );
			if ( persister.isVersionPropertyGenerated() ) {
				version = Versioning.getVersion( getState(), persister );
			}
			entry.postUpdate( instance, getState(), version );
		}

		persistenceContext.registerInsertedKey( persister, getId() );
	}

	final SessionFactoryImplementor factory = session.getFactory();

	if ( isCachePutEnabled( persister, session ) ) {
		final CacheEntry ce = persister.buildCacheEntry(
				instance,
				getState(),
				version,
				session
		);
		cacheEntry = persister.getCacheEntryStructure().structure( ce );
		final EntityDataAccess cache = persister.getCacheAccessStrategy();
		final Object ck = cache.generateCacheKey( id, persister, factory, session.getTenantIdentifier() );

		final boolean put = cacheInsert( persister, ck );

		if ( put && factory.getStatistics().isStatisticsEnabled() ) {
			factory.getStatistics().entityCachePut(
					StatsHelper.INSTANCE.getRootEntityRole( persister ),
					cache.getRegion().getName()
			);
		}
	}

	handleNaturalIdPostSaveNotifications( id );

	postInsert();

	if ( factory.getStatistics().isStatisticsEnabled() && !veto ) {
		factory.getStatistics().insertEntity( getPersister().getEntityName() );
	}

	markExecuted();
}
 
Example 13
Source File: CollectionType.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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, SharedSessionContractImplementor session, Object owner, Boolean overridingEager) {

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

	// 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 ) {

			collection = persistenceContext.getCollection( 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:
				boolean eager = overridingEager != null ? overridingEager : !persister.isLazy();
				if ( initializeImmediately() ) {
					session.initializeCollection( collection, false );
				}
				else if ( eager ) {
					persistenceContext.addNonLazyCollection( collection );
				}

				if ( hasHolder() ) {
					session.getPersistenceContext().addCollectionHolder( collection );
				}
			}

		}

		if ( LOG.isTraceEnabled() ) {
			LOG.tracef( "Created collection wrapper: %s",
					MessageHelper.collectionInfoString( persister, collection,
							key, session ) );
		}

	}

	collection.setOwner(owner);

	return collection.getValue();
}
 
Example 14
Source File: DynamicBatchingEntityLoaderBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public List doEntityBatchFetch(
		SharedSessionContractImplementor session,
		QueryParameters queryParameters,
		Serializable[] ids) {
	final String sql = StringHelper.expandBatchIdPlaceholder(
			sqlTemplate,
			ids,
			alias,
			persister.getKeyColumnNames(),
			session.getJdbcServices().getJdbcEnvironment().getDialect()
	);

	try {
		final PersistenceContext persistenceContext = session.getPersistenceContext();
		boolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();
		if ( queryParameters.isReadOnlyInitialized() ) {
			// The read-only/modifiable mode for the query was explicitly set.
			// Temporarily set the default read-only/modifiable setting to the query's setting.
			persistenceContext.setDefaultReadOnly( queryParameters.isReadOnly() );
		}
		else {
			// The read-only/modifiable setting for the query was not initialized.
			// Use the default read-only/modifiable from the persistence context instead.
			queryParameters.setReadOnly( persistenceContext.isDefaultReadOnly() );
		}
		persistenceContext.beforeLoad();
		List results;
		try {
			try {
				results = doTheLoad( sql, queryParameters, session );
			}
			finally {
				persistenceContext.afterLoad();
			}
			persistenceContext.initializeNonLazyCollections();
			log.debug( "Done batch load" );
			return results;
		}
		finally {
			// Restore the original default
			persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );
		}
	}
	catch ( SQLException sqle ) {
		throw session.getJdbcServices().getSqlExceptionHelper().convert(
				sqle,
				"could not load an entity batch: " + MessageHelper.infoString(
						getEntityPersisters()[0],
						ids,
						session.getFactory()
				),
				sql
		);
	}
}
 
Example 15
Source File: ForumServiceImpl.java    From high-performance-java-persistence with Apache License 2.0 4 votes vote down vote up
private org.hibernate.engine.spi.PersistenceContext getHibernatePersistenceContext() {
    SharedSessionContractImplementor session = entityManager.unwrap(
        SharedSessionContractImplementor.class
    );
    return session.getPersistenceContext();
}
 
Example 16
Source File: ForumServiceImpl.java    From high-performance-java-persistence with Apache License 2.0 4 votes vote down vote up
private org.hibernate.engine.spi.PersistenceContext getHibernatePersistenceContext() {
    SharedSessionContractImplementor session = entityManager.unwrap(
        SharedSessionContractImplementor.class
    );
    return session.getPersistenceContext();
}
 
Example 17
Source File: TwoPhaseLoad.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Perform the second step of 2-phase load. Fully initialize the entity
 * instance.
 * <p/>
 * After processing a JDBC result set, we "resolve" all the associations
 * between the entities which were instantiated and had their state
 * "hydrated" into an array
 *
 * @param entity The entity being loaded
 * @param readOnly Is the entity being loaded as read-only
 * @param session The Session
 * @param preLoadEvent The (re-used) pre-load event
 */
public static void initializeEntity(
		final Object entity,
		final boolean readOnly,
		final SharedSessionContractImplementor session,
		final PreLoadEvent preLoadEvent) {
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	final EntityEntry entityEntry = persistenceContext.getEntry( entity );
	if ( entityEntry == null ) {
		throw new AssertionFailure( "possible non-threadsafe access to the session" );
	}
	doInitializeEntity( entity, entityEntry, readOnly, session, preLoadEvent );
}