org.hibernate.engine.spi.PersistenceContext Java Examples

The following examples show how to use org.hibernate.engine.spi.PersistenceContext. 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: ImmutableEntityEntry.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This for is used during custom deserialization handling
 */
@SuppressWarnings( {"JavaDoc"})
private ImmutableEntityEntry(
		final SessionFactoryImplementor factory,
		final String entityName,
		final Serializable id,
		final Status status,
		final Status previousStatus,
		final Object[] loadedState,
		final Object[] deletedState,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final boolean isBeingReplicated,
		final PersistenceContext persistenceContext) {

	super( factory, entityName, id, status, previousStatus, loadedState, deletedState,
			version, lockMode, existsInDatabase, isBeingReplicated, persistenceContext
	);
}
 
Example #2
Source File: AbstractFlushingEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
	 * process cascade save/update at the start of a flush to discover
	 * any newly referenced entity that must be passed to saveOrUpdate(),
	 * and also apply orphan delete
	 */
	private void prepareEntityFlushes(EventSource session, PersistenceContext persistenceContext) throws HibernateException {

		LOG.debug( "Processing flush-time cascades" );

		final Object anything = getAnything();
		//safe from concurrent modification because of how concurrentEntries() is implemented on IdentityMap
		for ( Map.Entry<Object,EntityEntry> me : persistenceContext.reentrantSafeEntityEntries() ) {
//		for ( Map.Entry me : IdentityMap.concurrentEntries( persistenceContext.getEntityEntries() ) ) {
			EntityEntry entry = (EntityEntry) me.getValue();
			Status status = entry.getStatus();
			if ( status == Status.MANAGED || status == Status.SAVING || status == Status.READ_ONLY ) {
				cascadeOnFlush( session, entry.getPersister(), me.getKey(), anything );
			}
		}
	}
 
Example #3
Source File: AbstractFlushingEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings( value = {"unchecked"} )
private void logFlushResults(FlushEvent event) {
	if ( !LOG.isDebugEnabled() ) {
		return;
	}
	final EventSource session = event.getSession();
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	LOG.debugf(
			"Flushed: %s insertions, %s updates, %s deletions to %s objects",
			session.getActionQueue().numberOfInsertions(),
			session.getActionQueue().numberOfUpdates(),
			session.getActionQueue().numberOfDeletions(),
			persistenceContext.getNumberOfManagedEntities()
	);
	LOG.debugf(
			"Flushed: %s (re)creations, %s updates, %s removals to %s collections",
			session.getActionQueue().numberOfCollectionCreations(),
			session.getActionQueue().numberOfCollectionUpdates(),
			session.getActionQueue().numberOfCollectionRemovals(),
			persistenceContext.getCollectionEntries().size()
	);
	new EntityPrinter( session.getFactory() ).toString(
			persistenceContext.getEntitiesByKey().entrySet()
	);
}
 
Example #4
Source File: AbstractEntityEntry.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @deprecated the tenantId and entityMode parameters where removed: this constructor accepts but ignores them.
 * Use the other constructor!
 */
@Deprecated
public AbstractEntityEntry(
		final Status status,
		final Object[] loadedState,
		final Object rowId,
		final Serializable id,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final EntityPersister persister,
		final EntityMode entityMode,
		final String tenantId,
		final boolean disableVersionIncrement,
		final PersistenceContext persistenceContext) {
	this( status, loadedState, rowId, id, version, lockMode, existsInDatabase,
			persister,disableVersionIncrement, persistenceContext
	);
}
 
Example #5
Source File: MutableEntityEntry.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Custom deserialization routine used during deserialization of a
 * Session/PersistenceContext for increased performance.
 *
 * @param ois The stream from which to read the entry.
 * @param persistenceContext The context being deserialized.
 *
 * @return The deserialized EntityEntry
 *
 * @throws java.io.IOException If a stream error occurs
 * @throws ClassNotFoundException If any of the classes declared in the stream
 * cannot be found
 */
public static EntityEntry deserialize(
		ObjectInputStream ois,
		PersistenceContext persistenceContext) throws IOException, ClassNotFoundException {
	String previousStatusString;
	return new MutableEntityEntry(
			persistenceContext.getSession().getFactory(),
			(String) ois.readObject(),
			(Serializable) ois.readObject(),
			Status.valueOf( (String) ois.readObject() ),
			( previousStatusString = (String) ois.readObject() ).length() == 0
					? null
					: Status.valueOf( previousStatusString ),
			(Object[]) ois.readObject(),
			(Object[]) ois.readObject(),
			ois.readObject(),
			LockMode.valueOf( (String) ois.readObject() ),
			ois.readBoolean(),
			ois.readBoolean(),
			persistenceContext
	);
}
 
Example #6
Source File: AbstractReactiveFlushingEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * process cascade save/update at the start of a flush to discover
 * any newly referenced entity that must be passed to saveOrUpdate(),
 * and also apply orphan delete
 */
private CompletionStage<Void> prepareEntityFlushes(EventSource session, PersistenceContext persistenceContext) throws HibernateException {

	LOG.debug( "Processing flush-time cascades" );

	CompletionStage<Void> stage = CompletionStages.nullFuture();
	final IdentitySet copiedAlready = new IdentitySet( 10 );
	//safe from concurrent modification because of how concurrentEntries() is implemented on IdentityMap
	for ( Map.Entry<Object, EntityEntry> me : persistenceContext.reentrantSafeEntityEntries() ) {
		EntityEntry entry = me.getValue();
		Status status = entry.getStatus();
		if ( status == Status.MANAGED || status == Status.SAVING || status == Status.READ_ONLY ) {
			stage = stage.thenCompose( v -> cascadeOnFlush( session, entry.getPersister(), me.getKey(), copiedAlready ) );
		}
	}
	return stage;
}
 
Example #7
Source File: MutableEntityEntry.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This for is used during custom deserialization handling
 */
@SuppressWarnings( {"JavaDoc"})
private MutableEntityEntry(
		final SessionFactoryImplementor factory,
		final String entityName,
		final Serializable id,
		final Status status,
		final Status previousStatus,
		final Object[] loadedState,
		final Object[] deletedState,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final boolean isBeingReplicated,
		final PersistenceContext persistenceContext) {
	super( factory, entityName, id, status, previousStatus, loadedState, deletedState,
			version, lockMode, existsInDatabase, isBeingReplicated, persistenceContext
	);
}
 
Example #8
Source File: DefaultReactiveLockEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void cascadeOnLock(LockEvent event, EntityPersister persister, Object entity) {
	EventSource source = event.getSession();
	final PersistenceContext persistenceContext = source.getPersistenceContextInternal();
	persistenceContext.incrementCascadeLevel();
	try {
		new Cascade(
				CascadingActions.LOCK,
				CascadePoint.AFTER_LOCK,
				persister,
				entity,
				event.getLockOptions(),
				source
		).cascade();
	}
	finally {
		persistenceContext.decrementCascadeLevel();
	}
}
 
Example #9
Source File: ImmutableEntityEntry.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public ImmutableEntityEntry(
		final Status status,
		final Object[] loadedState,
		final Object rowId,
		final Serializable id,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final EntityPersister persister,
		final boolean disableVersionIncrement,
		final PersistenceContext persistenceContext) {

	super(
			status,
			loadedState,
			rowId,
			id,
			version,
			lockMode,
			existsInDatabase,
			persister,
			disableVersionIncrement,
			// purposefully do not pass along the session/persistence-context : HHH-10251
			null
	);
}
 
Example #10
Source File: ImmutableEntityEntry.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Custom deserialization routine used during deserialization of a
 * Session/PersistenceContext for increased performance.
 *
 * @param ois The stream from which to read the entry.
 * @param persistenceContext The context being deserialized.
 *
 * @return The deserialized EntityEntry
 *
 * @throws java.io.IOException If a stream error occurs
 * @throws ClassNotFoundException If any of the classes declared in the stream
 * cannot be found
 */
public static EntityEntry deserialize(
		ObjectInputStream ois,
		PersistenceContext persistenceContext) throws IOException, ClassNotFoundException {
	String previousStatusString;
	return new ImmutableEntityEntry(
			persistenceContext.getSession().getFactory(),
			(String) ois.readObject(),
			(Serializable) ois.readObject(),
			Status.valueOf( (String) ois.readObject() ),
			( previousStatusString = (String) ois.readObject() ).length() == 0
					? null
					: Status.valueOf( previousStatusString ),
			(Object[]) ois.readObject(),
			(Object[]) ois.readObject(),
			ois.readObject(),
			LockMode.valueOf( (String) ois.readObject() ),
			ois.readBoolean(),
			ois.readBoolean(),
			null
	);
}
 
Example #11
Source File: Collections.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void processNeverReferencedCollection(PersistentCollection coll, SessionImplementor session)
		throws HibernateException {
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	final CollectionEntry entry = persistenceContext.getCollectionEntry( coll );

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf(
				"Found collection with unloaded owner: %s",
				MessageHelper.collectionInfoString( 
						entry.getLoadedPersister(),
						coll,
						entry.getLoadedKey(),
						session
				)
		);
	}

	entry.setCurrentPersister( entry.getLoadedPersister() );
	entry.setCurrentKey( entry.getLoadedKey() );

	prepareCollectionForUpdate( coll, entry, session.getFactory() );

}
 
Example #12
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 #13
Source File: MutableEntityEntryFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public EntityEntry createEntityEntry(
		Status status,
		Object[] loadedState,
		Object rowId,
		Serializable id,
		Object version,
		LockMode lockMode,
		boolean existsInDatabase,
		EntityPersister persister,
		boolean disableVersionIncrement,
		PersistenceContext persistenceContext) {
	return new MutableEntityEntry(
			status,
			loadedState,
			rowId,
			id,
			version,
			lockMode,
			existsInDatabase,
			persister,
			disableVersionIncrement,
			persistenceContext
	);
}
 
Example #14
Source File: ForumServiceImpl.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Post> findAllByTitle(String title) {
    List<Post> posts = postDAO.findByTitle(title);

    Session session = sessionFactory.getCurrentSession();
    PersistenceContext persistenceContext = ((SharedSessionContractImplementor) session)
            .getPersistenceContext();

    for(Post post : posts) {
        assertTrue(session.contains(post));

        EntityEntry entityEntry = persistenceContext.getEntry(post);
        assertNull(entityEntry.getLoadedState());
    }

    return posts;
}
 
Example #15
Source File: ImmutableEntityEntryFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public EntityEntry createEntityEntry(
		Status status,
		Object[] loadedState,
		Object rowId,
		Serializable id,
		Object version,
		LockMode lockMode,
		boolean existsInDatabase,
		EntityPersister persister,
		boolean disableVersionIncrement,
		PersistenceContext persistenceContext) {
	return new ImmutableEntityEntry(
			status,
			loadedState,
			rowId,
			id,
			version,
			lockMode,
			existsInDatabase,
			persister,
			disableVersionIncrement,
			persistenceContext
	);
}
 
Example #16
Source File: MutableEntityEntry.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @deprecated the tenantId and entityMode parameters where removed: this constructor accepts but ignores them.
 * Use the other constructor!
 */
@Deprecated
public MutableEntityEntry(
		final Status status,
		final Object[] loadedState,
		final Object rowId,
		final Serializable id,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final EntityPersister persister,
		final EntityMode entityMode,
		final String tenantId,
		final boolean disableVersionIncrement,
		final PersistenceContext persistenceContext) {
	this( status, loadedState, rowId, id, version, lockMode, existsInDatabase,
			persister,disableVersionIncrement, persistenceContext
	);
}
 
Example #17
Source File: ForumServiceImpl.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public Post findById(Long id) {
    Post post = postDAO.findById(id);

    Session session = sessionFactory.getCurrentSession();
    PersistenceContext persistenceContext = ((SharedSessionContractImplementor) session)
        .getPersistenceContext();

    EntityEntry entityEntry = persistenceContext.getEntry(post);
    assertNotNull(entityEntry.getLoadedState());

    return post;
}
 
Example #18
Source File: DefaultLoadEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * If there is already a corresponding proxy associated with the
 * persistence context, return it; otherwise create a proxy, associate it
 * with the persistence context, and return the just-created proxy.
 *
 * @param event The initiating load request event
 * @param persister The persister corresponding to the entity to be loaded
 * @param keyToLoad The key of the entity to be loaded
 * @param options The defined load options
 * @param persistenceContext The originating session
 *
 * @return The created/existing proxy
 */
private Object createProxyIfNecessary(
		final LoadEvent event,
		final EntityPersister persister,
		final EntityKey keyToLoad,
		final LoadEventListener.LoadType options,
		final PersistenceContext persistenceContext) {
	Object existing = persistenceContext.getEntity( keyToLoad );
	if ( existing != null ) {
		// return existing object or initialized proxy (unless deleted)
		if ( traceEnabled ) {
			LOG.trace( "Entity found in session cache" );
		}
		if ( options.isCheckDeleted() ) {
			EntityEntry entry = persistenceContext.getEntry( existing );
			Status status = entry.getStatus();
			if ( status == Status.DELETED || status == Status.GONE ) {
				return null;
			}
		}
		return existing;
	}
	if ( traceEnabled ) {
		LOG.trace( "Creating new proxy for entity" );
	}
	// return new uninitialized proxy
	Object proxy = persister.createProxy( event.getEntityId(), event.getSession() );
	persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey( keyToLoad );
	persistenceContext.addProxy( keyToLoad, proxy );
	return proxy;
}
 
Example #19
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 #20
Source File: AbstractEntityEntry.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings( {"JavaDoc"})
protected AbstractEntityEntry(
		final SessionFactoryImplementor factory,
		final String entityName,
		final Serializable id,
		final Status status,
		final Status previousStatus,
		final Object[] loadedState,
		final Object[] deletedState,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final boolean isBeingReplicated,
		final PersistenceContext persistenceContext) {
	this.persister = ( factory == null ? null : factory.getEntityPersister( entityName ) );
	this.id = id;
	setCompressedValue( EnumState.STATUS, status );
	setCompressedValue( EnumState.PREVIOUS_STATUS, previousStatus );
	this.loadedState = loadedState;
	setDeletedState( deletedState );
	this.version = version;
	setCompressedValue( EnumState.LOCK_MODE, lockMode );
	setCompressedValue( BooleanState.EXISTS_IN_DATABASE, existsInDatabase );
	setCompressedValue( BooleanState.IS_BEING_REPLICATED, isBeingReplicated );
	this.rowId = null; // this is equivalent to the old behavior...
	this.persistenceContext = persistenceContext;
}
 
Example #21
Source File: AbstractReactiveFlushingEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Initialize the flags of the CollectionEntry, including the
 * dirty check.
 */
private void prepareCollectionFlushes(PersistenceContext persistenceContext) throws HibernateException {

	// Initialize dirty flags for arrays + collections with composite elements
	// and reset reached, doupdate, etc.

	LOG.debug( "Dirty checking collections" );
	persistenceContext.forEachCollectionEntry( (pc,ce) -> ce.preFlush( pc ), true );
}
 
Example #22
Source File: AbstractReactiveFlushingEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 1. detect any dirty entities
 * 2. schedule any entity updates
 * 3. search out any reachable collections
 */
private int flushEntities(final FlushEvent event, final PersistenceContext persistenceContext) throws HibernateException {

	LOG.trace( "Flushing entities and processing referenced collections" );

	final EventSource source = event.getSession();
	final Iterable<FlushEntityEventListener> flushListeners =
			source.getFactory().getServiceRegistry()
					.getService( EventListenerRegistry.class )
					.getEventListenerGroup( EventType.FLUSH_ENTITY )
					.listeners();

	// Among other things, updateReachables() will recursively load all
	// collections that are moving roles. This might cause entities to
	// be loaded.

	// So this needs to be safe from concurrent modification problems.

	final Map.Entry<Object,EntityEntry>[] entityEntries = persistenceContext.reentrantSafeEntityEntries();
	final int count = entityEntries.length;

	for ( Map.Entry<Object,EntityEntry> me : entityEntries ) {

		// Update the status of the object and if necessary, schedule an update

		EntityEntry entry = me.getValue();
		Status status = entry.getStatus();

		if ( status != Status.LOADING && status != Status.GONE ) {
			final FlushEntityEvent entityEvent = new FlushEntityEvent( source, me.getKey(), entry );
			for ( FlushEntityEventListener listener : flushListeners ) {
				listener.onFlushEntity( entityEvent );
			}
		}
	}

	source.getActionQueue().sortActions();

	return count;
}
 
Example #23
Source File: MutableEntityEntry.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public MutableEntityEntry(
		final Status status,
		final Object[] loadedState,
		final Object rowId,
		final Serializable id,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final EntityPersister persister,
		final boolean disableVersionIncrement,
		final PersistenceContext persistenceContext) {
	super( status, loadedState, rowId, id, version, lockMode, existsInDatabase, persister,
			disableVersionIncrement, persistenceContext
	);
}
 
Example #24
Source File: AbstractEntityEntry.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public AbstractEntityEntry(
		final Status status,
		final Object[] loadedState,
		final Object rowId,
		final Serializable id,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final EntityPersister persister,
		final boolean disableVersionIncrement,
		final PersistenceContext persistenceContext) {
	setCompressedValue( EnumState.STATUS, status );
	// not useful strictly speaking but more explicit
	setCompressedValue( EnumState.PREVIOUS_STATUS, null );
	// only retain loaded state if the status is not Status.READ_ONLY
	if ( status != Status.READ_ONLY ) {
		this.loadedState = loadedState;
	}
	this.id=id;
	this.rowId=rowId;
	setCompressedValue( BooleanState.EXISTS_IN_DATABASE, existsInDatabase );
	this.version=version;
	setCompressedValue( EnumState.LOCK_MODE, lockMode );
	setCompressedValue( BooleanState.IS_BEING_REPLICATED, disableVersionIncrement );
	this.persister=persister;
	this.persistenceContext = persistenceContext;
}
 
Example #25
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 #26
Source File: DefaultLoadEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a proxy, initialize it and/or narrow it provided either
 * is necessary.
 *
 * @param event The initiating load request event
 * @param persister The persister corresponding to the entity to be loaded
 * @param keyToLoad The key of the entity to be loaded
 * @param options The defined load options
 * @param persistenceContext The originating session
 * @param proxy The proxy to narrow
 *
 * @return The created/existing proxy
 */
private Object returnNarrowedProxy(
		final LoadEvent event,
		final EntityPersister persister,
		final EntityKey keyToLoad,
		final LoadEventListener.LoadType options,
		final PersistenceContext persistenceContext,
		final Object proxy) {
	if ( traceEnabled ) {
		LOG.trace( "Entity proxy found in session cache" );
	}
	LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
	if ( li.isUnwrap() ) {
		return li.getImplementation();
	}
	Object impl = null;
	if ( !options.isAllowProxyCreation() ) {
		impl = load( event, persister, keyToLoad, options );
		if ( impl == null ) {
			event.getSession()
					.getFactory()
					.getEntityNotFoundDelegate()
					.handleEntityNotFound( persister.getEntityName(), keyToLoad.getIdentifier() );
		}
	}
	return persistenceContext.narrowProxy( proxy, persister, keyToLoad, impl );
}
 
Example #27
Source File: DefaultLoadEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Based on configured options, will either return a pre-existing proxy,
 * generate a new proxy, or perform an actual load.
 *
 * @param event The initiating load request event
 * @param persister The persister corresponding to the entity to be loaded
 * @param keyToLoad The key of the entity to be loaded
 * @param options The defined load options
 *
 * @return The result of the proxy/load operation.
 */
private Object proxyOrLoad(
		final LoadEvent event,
		final EntityPersister persister,
		final EntityKey keyToLoad,
		final LoadEventListener.LoadType options) {

	if ( traceEnabled ) {
		LOG.tracev(
				"Loading entity: {0}",
				MessageHelper.infoString( persister, event.getEntityId(), event.getSession().getFactory() )
		);
	}

	// this class has no proxies (so do a shortcut)
	if ( !persister.hasProxy() ) {
		return load( event, persister, keyToLoad, options );
	}

	final PersistenceContext persistenceContext = event.getSession().getPersistenceContext();

	// look for a proxy
	Object proxy = persistenceContext.getProxy( keyToLoad );
	if ( proxy != null ) {
		return returnNarrowedProxy( event, persister, keyToLoad, options, persistenceContext, proxy );
	}

	if ( options.isAllowProxyCreation() ) {
		return createProxyIfNecessary( event, persister, keyToLoad, options, persistenceContext );
	}

	// return a newly loaded object
	return load( event, persister, keyToLoad, options );
}
 
Example #28
Source File: ImmutableEntityEntry.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @deprecated the tenantId and entityMode parameters where removed: this constructor accepts but ignores them.
 * Use the other constructor!
 */
@Deprecated
public ImmutableEntityEntry(
		final Status status,
		final Object[] loadedState,
		final Object rowId,
		final Serializable id,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final EntityPersister persister,
		final EntityMode entityMode,
		final String tenantId,
		final boolean disableVersionIncrement,
		final PersistenceContext persistenceContext) {
	this(
			status,
			loadedState,
			rowId,
			id,
			version,
			lockMode,
			existsInDatabase,
			persister,
			disableVersionIncrement,
			// purposefully do not pass along the session/persistence-context : HHH-10251
			null
	);
}
 
Example #29
Source File: DefaultFlushEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** Handle the given flush event.
 *
 * @param event The flush event to be handled.
 * @throws HibernateException
 */
public void onFlush(FlushEvent event) throws HibernateException {
	final EventSource source = event.getSession();
	final PersistenceContext persistenceContext = source.getPersistenceContext();

	if ( persistenceContext.getNumberOfManagedEntities() > 0 ||
			persistenceContext.getCollectionEntries().size() > 0 ) {

		try {
			source.getEventListenerManager().flushStart();

			flushEverythingToExecutions( event );
			performExecutions( source );
			postFlush( source );
		}
		finally {
			source.getEventListenerManager().flushEnd(
					event.getNumberOfEntitiesProcessed(),
					event.getNumberOfCollectionsProcessed()
			);
		}

		postPostFlush( source );

		if ( source.getFactory().getStatistics().isStatisticsEnabled() ) {
			source.getFactory().getStatistics().flush();
		}
	}
}
 
Example #30
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected final Serializable resolveNaturalId(Map<String, Object> naturalIdParameters) {
	performAnyNeededCrossReferenceSynchronizations();

	final ResolveNaturalIdEvent event =
			new ResolveNaturalIdEvent( naturalIdParameters, entityPersister, SessionImpl.this );
	fireResolveNaturalId( event );

	if ( event.getEntityId() == PersistenceContext.NaturalIdHelper.INVALID_NATURAL_ID_REFERENCE ) {
		return null;
	}
	else {
		return event.getEntityId();
	}
}