Java Code Examples for org.hibernate.engine.spi.EntityEntry#getPersister()

The following examples show how to use org.hibernate.engine.spi.EntityEntry#getPersister() . 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: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private Object[] getValues(Object entity, EntityEntry entry, boolean mightBeDirty, SessionImplementor session) {
	final Object[] loadedState = entry.getLoadedState();
	final Status status = entry.getStatus();
	final EntityPersister persister = entry.getPersister();

	final Object[] values;
	if ( status == Status.DELETED ) {
		//grab its state saved at deletion
		values = entry.getDeletedState();
	}
	else if ( !mightBeDirty && loadedState != null ) {
		values = loadedState;
	}
	else {
		checkId( entity, persister, entry.getId(), session );

		// grab its current state
		values = persister.getPropertyValues( entity );

		checkNaturalId( persister, entry, values, loadedState, session );
	}
	return values;
}
 
Example 2
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected boolean handleInterception(FlushEntityEvent event) {
	SessionImplementor session = event.getSession();
	EntityEntry entry = event.getEntityEntry();
	EntityPersister persister = entry.getPersister();
	Object entity = event.getEntity();

	//give the Interceptor a chance to modify property values
	final Object[] values = event.getPropertyValues();
	final boolean intercepted = invokeInterceptor( session, entity, entry, values, persister );

	//now we might need to recalculate the dirtyProperties array
	if ( intercepted && event.isDirtyCheckPossible() ) {
		dirtyCheck( event );
	}

	return intercepted;
}
 
Example 3
Source File: OptimisticLockingChildUpdatesRootVersionTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
private boolean updated(FlushEntityEvent event) {
    final EntityEntry entry = event.getEntityEntry();
    final Object entity = event.getEntity();

    int[] dirtyProperties;
    EntityPersister persister = entry.getPersister();
    final Object[] values = event.getPropertyValues();
    SessionImplementor session = event.getSession();

    if ( event.hasDatabaseSnapshot() ) {
        dirtyProperties = persister.findModified( event.getDatabaseSnapshot(), values, entity, session );
    }
    else {
        dirtyProperties = persister.findDirty( values, entry.getLoadedState(), entity, session );
    }

    return dirtyProperties != null;
}
 
Example 4
Source File: OptimisticLockingBidirectionalChildUpdatesRootVersionTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
private boolean updated(FlushEntityEvent event) {
    final EntityEntry entry = event.getEntityEntry();
    final Object entity = event.getEntity();

    int[] dirtyProperties;
    EntityPersister persister = entry.getPersister();
    final Object[] values = event.getPropertyValues();
    SessionImplementor session = event.getSession();

    if ( event.hasDatabaseSnapshot() ) {
        dirtyProperties = persister.findModified( event.getDatabaseSnapshot(), values, entity, session );
    }
    else {
        dirtyProperties = persister.findDirty( values, entry.getLoadedState(), entity, session );
    }

    return dirtyProperties != null;
}
 
Example 5
Source File: PessimisticForceIncrementLockingStrategy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void lock(Serializable id, Object version, Object object, int timeout, SharedSessionContractImplementor session) {
	if ( !lockable.isVersioned() ) {
		throw new HibernateException( "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
	}
	final EntityEntry entry = session.getPersistenceContext().getEntry( object );
	final EntityPersister persister = entry.getPersister();
	final Object nextVersion = persister.forceVersionIncrement( entry.getId(), entry.getVersion(), session );
	entry.forceLocked( object, nextVersion );
}
 
Example 6
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Flushes a single entity's state to the database, by scheduling
 * an update action, if necessary
 */
public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
	final Object entity = event.getEntity();
	final EntityEntry entry = event.getEntityEntry();
	final EventSource session = event.getSession();
	final EntityPersister persister = entry.getPersister();
	final Status status = entry.getStatus();
	final Type[] types = persister.getPropertyTypes();

	final boolean mightBeDirty = entry.requiresDirtyCheck( entity );

	final Object[] values = getValues( entity, entry, mightBeDirty, session );

	event.setPropertyValues( values );

	//TODO: avoid this for non-new instances where mightBeDirty==false
	boolean substitute = wrapCollections( session, persister, types, values );

	if ( isUpdateNecessary( event, mightBeDirty ) ) {
		substitute = scheduleUpdate( event ) || substitute;
	}

	if ( status != Status.DELETED ) {
		// now update the object .. has to be outside the main if block above (because of collections)
		if ( substitute ) {
			persister.setPropertyValues( entity, values );
		}

		// Search for collections by reachability, updating their role.
		// We don't want to touch collections reachable from a deleted object
		if ( persister.hasCollections() ) {
			new FlushVisitor( session, entity ).processEntityPropertyValues( values, types );
		}
	}

}
 
Example 7
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convenience method to retrieve an entities next version value
 */
private Object getNextVersion(FlushEntityEvent event) throws HibernateException {

	EntityEntry entry = event.getEntityEntry();
	EntityPersister persister = entry.getPersister();
	if ( persister.isVersioned() ) {

		Object[] values = event.getPropertyValues();

		if ( entry.isBeingReplicated() ) {
			return Versioning.getVersion( values, persister );
		}
		else {
			int[] dirtyProperties = event.getDirtyProperties();

			final boolean isVersionIncrementRequired = isVersionIncrementRequired(
					event,
					entry,
					persister,
					dirtyProperties
			);

			final Object nextVersion = isVersionIncrementRequired ?
					Versioning.increment( entry.getVersion(), persister.getVersionType(), event.getSession() ) :
					entry.getVersion(); //use the current version

			Versioning.setVersion( values, nextVersion, persister );

			return nextVersion;
		}
	}
	else {
		return null;
	}

}
 
Example 8
Source File: DefaultPostLoadEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onPostLoad(PostLoadEvent event) {
	final Object entity = event.getEntity();

	callbackRegistry.postLoad( entity );

	final EntityEntry entry = event.getSession().getPersistenceContext().getEntry( entity );
	if ( entry == null ) {
		throw new AssertionFailure( "possible non-threadsafe access to the session" );
	}

	final LockMode lockMode = entry.getLockMode();
	if ( LockMode.PESSIMISTIC_FORCE_INCREMENT.equals( lockMode ) ) {
		final EntityPersister persister = entry.getPersister();
		final Object nextVersion = persister.forceVersionIncrement(
				entry.getId(),
				entry.getVersion(),
				event.getSession()
		);
		entry.forceLocked( entity, nextVersion );
	}
	else if ( LockMode.OPTIMISTIC_FORCE_INCREMENT.equals( lockMode ) ) {
		final EntityIncrementVersionProcess incrementVersion = new EntityIncrementVersionProcess( entity, entry );
		event.getSession().getActionQueue().registerProcess( incrementVersion );
	}
	else if ( LockMode.OPTIMISTIC.equals( lockMode ) ) {
		final EntityVerifyVersionProcess verifyVersion = new EntityVerifyVersionProcess( entity, entry );
		event.getSession().getActionQueue().registerProcess( verifyVersion );
	}

	if ( event.getPersister().implementsLifecycle() ) {
		//log.debug( "calling onLoad()" );
		( (Lifecycle) event.getEntity() ).onLoad( event.getSession(), event.getId() );
	}

}
 
Example 9
Source File: DefaultReactiveLockEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Performs a pessimistic lock upgrade on a given entity, if needed.
 *
 * @param object The entity for which to upgrade the lock.
 * @param entry The entity's EntityEntry instance.
 * @param lockOptions contains the requested lock mode.
 * @param source The session which is the source of the event being processed.
 */
protected CompletionStage<Void> upgradeLock(Object object, EntityEntry entry,
											LockOptions lockOptions,
											EventSource source) {

	LockMode requestedLockMode = lockOptions.getLockMode();
	if ( requestedLockMode.greaterThan( entry.getLockMode() ) ) {
		// The user requested a "greater" (i.e. more restrictive) form of
		// pessimistic lock

		if ( entry.getStatus() != Status.MANAGED ) {
			throw new ObjectDeletedException(
					"attempted to lock a deleted instance",
					entry.getId(),
					entry.getPersister().getEntityName()
			);
		}

		final EntityPersister persister = entry.getPersister();

		if ( log.isTraceEnabled() ) {
			log.tracev(
					"Locking {0} in mode: {1}",
					MessageHelper.infoString( persister, entry.getId(), source.getFactory() ),
					requestedLockMode
			);
		}

		final boolean cachingEnabled = persister.canWriteToCache();
		final SoftLock lock;
		final Object ck;
		if ( cachingEnabled ) {
			EntityDataAccess cache = persister.getCacheAccessStrategy();
			ck = cache.generateCacheKey(
					entry.getId(),
					persister,
					source.getFactory(),
					source.getTenantIdentifier()
			);
			lock = cache.lockItem( source, ck, entry.getVersion() );
		}
		else {
			lock = null;
			ck = null;
		}

		return ((ReactiveEntityPersister) persister).lockReactive(
				entry.getId(),
				entry.getVersion(),
				object,
				lockOptions,
				source
		).thenAccept( v -> entry.setLockMode(requestedLockMode) )
				.whenComplete( (r, e) -> {
					// the database now holds a lock + the object is flushed from the cache,
					// so release the soft lock
					if ( cachingEnabled ) {
						persister.getCacheAccessStrategy().unlockItem( source, ck, lock );
					}
				} );

	}
	else {
		return CompletionStages.nullFuture();
	}
}
 
Example 10
Source File: AbstractLockUpgradeEventListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs a pessimistic lock upgrade on a given entity, if needed.
 *
 * @param object The entity for which to upgrade the lock.
 * @param entry The entity's EntityEntry instance.
 * @param lockOptions contains the requested lock mode.
 * @param source The session which is the source of the event being processed.
 */
protected void upgradeLock(Object object, EntityEntry entry, LockOptions lockOptions, EventSource source) {

	LockMode requestedLockMode = lockOptions.getLockMode();
	if ( requestedLockMode.greaterThan( entry.getLockMode() ) ) {
		// The user requested a "greater" (i.e. more restrictive) form of
		// pessimistic lock

		if ( entry.getStatus() != Status.MANAGED ) {
			throw new ObjectDeletedException(
					"attempted to lock a deleted instance",
					entry.getId(),
					entry.getPersister().getEntityName()
			);
		}

		final EntityPersister persister = entry.getPersister();

		if ( log.isTraceEnabled() ) {
			log.tracev(
					"Locking {0} in mode: {1}",
					MessageHelper.infoString( persister, entry.getId(), source.getFactory() ),
					requestedLockMode
			);
		}

		final boolean cachingEnabled = persister.canWriteToCache();
		SoftLock lock = null;
		Object ck = null;
		try {
			if ( cachingEnabled ) {
				EntityDataAccess cache = persister.getCacheAccessStrategy();
				ck = cache.generateCacheKey( entry.getId(), persister, source.getFactory(), source.getTenantIdentifier() );
				lock = cache.lockItem( source, ck, entry.getVersion() );
			}

			if ( persister.isVersioned() && requestedLockMode == LockMode.FORCE  ) {
				// todo : should we check the current isolation mode explicitly?
				Object nextVersion = persister.forceVersionIncrement(
						entry.getId(), entry.getVersion(), source
				);
				entry.forceLocked( object, nextVersion );
			}
			else {
				persister.lock( entry.getId(), entry.getVersion(), object, lockOptions, source );
			}
			entry.setLockMode(requestedLockMode);
		}
		finally {
			// the database now holds a lock + the object is flushed from the cache,
			// so release the soft lock
			if ( cachingEnabled ) {
				persister.getCacheAccessStrategy().unlockItem( source, ck, lock );
			}
		}

	}
}
 
Example 11
Source File: DefaultDeleteEventListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Handle the given delete event.  This is the cascaded form.
 *
 * @param event The delete event.
 * @param transientEntities The cache of entities already deleted
 *
 * @throws HibernateException
 */
public void onDelete(DeleteEvent event, Set transientEntities) throws HibernateException {

	final EventSource source = event.getSession();

	final PersistenceContext persistenceContext = source.getPersistenceContext();
	Object entity = persistenceContext.unproxyAndReassociate( event.getObject() );

	EntityEntry entityEntry = persistenceContext.getEntry( entity );
	final EntityPersister persister;
	final Serializable id;
	final Object version;

	if ( entityEntry == null ) {
		LOG.trace( "Entity was not persistent in delete processing" );

		persister = source.getEntityPersister( event.getEntityName(), entity );

		if ( ForeignKeys.isTransient( persister.getEntityName(), entity, null, source ) ) {
			deleteTransientEntity( source, entity, event.isCascadeDeleteEnabled(), persister, transientEntities );
			// EARLY EXIT!!!
			return;
		}
		performDetachedEntityDeletionCheck( event );

		id = persister.getIdentifier( entity, source );

		if ( id == null ) {
			throw new TransientObjectException(
					"the detached instance passed to delete() had a null identifier"
			);
		}

		final EntityKey key = source.generateEntityKey( id, persister );

		persistenceContext.checkUniqueness( key, entity );

		new OnUpdateVisitor( source, id, entity ).process( entity, persister );

		version = persister.getVersion( entity );

		entityEntry = persistenceContext.addEntity(
				entity,
				(persister.isMutable() ? Status.MANAGED : Status.READ_ONLY),
				persister.getPropertyValues( entity ),
				key,
				version,
				LockMode.NONE,
				true,
				persister,
				false
		);
	}
	else {
		LOG.trace( "Deleting a persistent instance" );

		if ( entityEntry.getStatus() == Status.DELETED || entityEntry.getStatus() == Status.GONE ) {
			LOG.trace( "Object was already deleted" );
			return;
		}
		persister = entityEntry.getPersister();
		id = entityEntry.getId();
		version = entityEntry.getVersion();
	}

	/*if ( !persister.isMutable() ) {
		throw new HibernateException(
				"attempted to delete an object of immutable class: " +
				MessageHelper.infoString(persister)
			);
	}*/

	if ( invokeDeleteLifecycle( source, entity, persister ) ) {
		return;
	}

	deleteEntity(
			source,
			entity,
			entityEntry,
			event.isCascadeDeleteEnabled(),
			event.isOrphanRemovalBeforeUpdates(),
			persister,
			transientEntities
	);

	if ( source.getFactory().getSettings().isIdentifierRollbackEnabled() ) {
		persister.resetIdentifier( entity, id, version, source );
	}
}
 
Example 12
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private boolean scheduleUpdate(final FlushEntityEvent event) {
	final EntityEntry entry = event.getEntityEntry();
	final EventSource session = event.getSession();
	final Object entity = event.getEntity();
	final Status status = entry.getStatus();
	final EntityPersister persister = entry.getPersister();
	final Object[] values = event.getPropertyValues();

	if ( LOG.isTraceEnabled() ) {
		if ( status == Status.DELETED ) {
			if ( !persister.isMutable() ) {
				LOG.tracev(
						"Updating immutable, deleted entity: {0}",
						MessageHelper.infoString( persister, entry.getId(), session.getFactory() )
				);
			}
			else if ( !entry.isModifiableEntity() ) {
				LOG.tracev(
						"Updating non-modifiable, deleted entity: {0}",
						MessageHelper.infoString( persister, entry.getId(), session.getFactory() )
				);
			}
			else {
				LOG.tracev(
						"Updating deleted entity: ",
						MessageHelper.infoString( persister, entry.getId(), session.getFactory() )
				);
			}
		}
		else {
			LOG.tracev(
					"Updating entity: {0}",
					MessageHelper.infoString( persister, entry.getId(), session.getFactory() )
			);
		}
	}

	final boolean intercepted = !entry.isBeingReplicated() && handleInterception( event );

	// increment the version number (if necessary)
	final Object nextVersion = getNextVersion( event );

	// if it was dirtied by a collection only
	int[] dirtyProperties = event.getDirtyProperties();
	if ( event.isDirtyCheckPossible() && dirtyProperties == null ) {
		if ( !intercepted && !event.hasDirtyCollection() ) {
			throw new AssertionFailure( "dirty, but no dirty properties" );
		}
		dirtyProperties = ArrayHelper.EMPTY_INT_ARRAY;
	}

	// check nullability but do not doAfterTransactionCompletion command execute
	// we'll use scheduled updates for that.
	new Nullability( session ).checkNullability( values, persister, true );

	// schedule the update
	// note that we intentionally do _not_ pass in currentPersistentState!
	session.getActionQueue().addAction(
			new EntityUpdateAction(
					entry.getId(),
					values,
					dirtyProperties,
					event.hasDirtyCollection(),
					( status == Status.DELETED && !entry.isModifiableEntity() ?
							persister.getPropertyValues( entity ) :
							entry.getLoadedState() ),
					entry.getVersion(),
					nextVersion,
					entity,
					entry.getRowId(),
					persister,
					session
			)
	);

	return intercepted;
}