Java Code Examples for org.hibernate.engine.spi.EntityKey#getIdentifier()

The following examples show how to use org.hibernate.engine.spi.EntityKey#getIdentifier() . 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: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The entity instance is already in the session cache
 */
private void instanceAlreadyLoaded(
		final ResultSet rs,
		final int i,
		final Loadable persister,
		final EntityKey key,
		final Object object,
		final LockMode requestedLockMode,
		final SharedSessionContractImplementor session)
		throws HibernateException, SQLException {
	if ( !persister.isInstance( object ) ) {
		throw new WrongClassException(
				"loaded object was of wrong class " + object.getClass(),
				key.getIdentifier(),
				persister.getEntityName()
		);
	}

	if ( LockMode.NONE != requestedLockMode && upgradeLocks() ) { //no point doing this if NONE was requested
		final EntityEntry entry = session.getPersistenceContext().getEntry( object );
		if ( entry.getLockMode().lessThan( requestedLockMode ) ) {
			//we only check the version when _upgrading_ lock modes
			if ( persister.isVersioned() ) {
				checkVersion( i, persister, key.getIdentifier(), object, rs, session );
			}
			//we need to upgrade the lock mode to the mode requested
			entry.setLockMode( requestedLockMode );
		}
	}
}
 
Example 2
Source File: EntityReferenceInitializerImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String getConcreteEntityTypeName(
		ResultSet resultSet,
		ResultSetProcessingContext context,
		EntityKey entityKey) {
	final Loadable loadable = (Loadable) entityReference.getEntityPersister();
	if ( ! loadable.hasSubclasses() ) {
		return entityReference.getEntityPersister().getEntityName();
	}

	final Object discriminatorValue;
	try {
		discriminatorValue = loadable.getDiscriminatorType().nullSafeGet(
				resultSet,
				entityReferenceAliases.getColumnAliases().getSuffixedDiscriminatorAlias(),
				context.getSession(),
				null
		);
	}
	catch (SQLException e) {
		throw context.getSession().getFactory().getServiceRegistry().getService( JdbcServices.class ).getSqlExceptionHelper().convert(
				e,
				"Could not read discriminator value from ResultSet"
		);
	}

	final String result = loadable.getSubclassForDiscriminatorValue( discriminatorValue );

	if ( result == null ) {
		// whoops! we got an instance of another class hierarchy branch
		throw new WrongClassException(
				"Discriminator: " + discriminatorValue,
				entityKey.getIdentifier(),
				entityReference.getEntityPersister().getEntityName()
		);
	}

	return result;
}
 
Example 3
Source File: EntityReferenceInitializerImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void checkVersion(
		SharedSessionContractImplementor session,
		ResultSet resultSet,
		EntityPersister persister,
		EntityAliases entityAliases,
		EntityKey entityKey,
		Object entityInstance) {
	final Object version = session.getPersistenceContext().getEntry( entityInstance ).getVersion();

	if ( version != null ) {
		//null version means the object is in the process of being loaded somewhere else in the ResultSet
		VersionType versionType = persister.getVersionType();
		final Object currentVersion;
		try {
			currentVersion = versionType.nullSafeGet(
					resultSet,
					entityAliases.getSuffixedVersionAliases(),
					session,
					null
			);
		}
		catch (SQLException e) {
			throw session.getFactory().getServiceRegistry().getService( JdbcServices.class ).getSqlExceptionHelper().convert(
					e,
					"Could not read version value from result set"
			);
		}

		if ( !versionType.isEqual( version, currentVersion ) ) {
			if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
				session.getFactory().getStatistics().optimisticFailure( persister.getEntityName() );
			}
			throw new StaleObjectStateException( persister.getEntityName(), entityKey.getIdentifier() );
		}
	}
}
 
Example 4
Source File: StatefulPersistenceContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void checkUniqueness(EntityKey key, Object object) throws HibernateException {
	final Object entity = getEntity( key );
	if ( entity == object ) {
		throw new AssertionFailure( "object already associated, but no entry was found" );
	}
	if ( entity != null ) {
		throw new NonUniqueObjectException( key.getIdentifier(), key.getEntityName() );
	}
}
 
Example 5
Source File: Loader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Hydrate the state an object from the SQL <tt>ResultSet</tt>, into
 * an array or "hydrated" values (do not resolve associations yet),
 * and pass the hydrates state to the session.
 */
private void loadFromResultSet(
		final ResultSet rs,
		final int i,
		final Object object,
		final String instanceEntityName,
		final EntityKey key,
		final String rowIdAlias,
		final LockMode lockMode,
		final Loadable rootPersister,
		final SharedSessionContractImplementor session) throws SQLException, HibernateException {

	final Serializable id = key.getIdentifier();

	// Get the persister for the _subclass_
	final Loadable persister = (Loadable) getFactory().getEntityPersister( instanceEntityName );

	if ( LOG.isTraceEnabled() ) {
		LOG.tracef(
				"Initializing object from ResultSet: %s",
				MessageHelper.infoString(
						persister,
						id,
						getFactory()
				)
		);
	}

	boolean fetchAllPropertiesRequested = isEagerPropertyFetchEnabled( i );

	// add temp entry so that the next step is circular-reference
	// safe - only needed because some types don't take proper
	// advantage of two-phase-load (esp. components)
	TwoPhaseLoad.addUninitializedEntity(
			key,
			object,
			persister,
			lockMode,
			session
	);

	//This is not very nice (and quite slow):
	final String[][] cols = persister == rootPersister ?
			getEntityAliases()[i].getSuffixedPropertyAliases() :
			getEntityAliases()[i].getSuffixedPropertyAliases( persister );

	final Object[] values = persister.hydrate(
			rs,
			id,
			object,
			rootPersister,
			cols,
			fetchAllPropertiesRequested,
			session
	);

	final Object rowId = persister.hasRowId() ? rs.getObject( rowIdAlias ) : null;

	final AssociationType[] ownerAssociationTypes = getOwnerAssociationTypes();
	if ( ownerAssociationTypes != null && ownerAssociationTypes[i] != null ) {
		String ukName = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName();
		if ( ukName != null ) {
			final int index = ( (UniqueKeyLoadable) persister ).getPropertyIndex( ukName );
			final Type type = persister.getPropertyTypes()[index];

			// polymorphism not really handled completely correctly,
			// perhaps...well, actually its ok, assuming that the
			// entity name used in the lookup is the same as the
			// the one used here, which it will be

			EntityUniqueKey euk = new EntityUniqueKey(
					rootPersister.getEntityName(), //polymorphism comment above
					ukName,
					type.semiResolve( values[index], session, object ),
					type,
					persister.getEntityMode(),
					session.getFactory()
			);
			session.getPersistenceContext().addEntity( euk, object );
		}
	}

	TwoPhaseLoad.postHydrate(
			persister,
			id,
			values,
			rowId,
			object,
			lockMode,
			session
	);

}
 
Example 6
Source File: EntityReferenceInitializerImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void hydrateEntityState(ResultSet resultSet, ResultSetProcessingContextImpl context) {
	final EntityReferenceProcessingState processingState = context.getProcessingState( entityReference );

	// If there is no identifier for this entity reference for this row, nothing to do
	if ( processingState.isMissingIdentifier() ) {
		handleMissingIdentifier( context );
		return;
	}

	// make sure we have the EntityKey
	final EntityKey entityKey = processingState.getEntityKey();
	if ( entityKey == null ) {
		handleMissingIdentifier( context );
		return;
	}

	// Have we already hydrated this entity's state?
	if ( processingState.getEntityInstance() != null ) {
		return;
	}


	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// In getting here, we know that:
	// 		1) We need to hydrate the entity state
	//		2) We have a valid EntityKey for the entity

	// see if we have an existing entry in the session for this EntityKey
	final Object existing = context.getSession().getEntityUsingInterceptor( entityKey );
	if ( existing != null ) {
		// It is previously associated with the Session, perform some checks
		if ( ! entityReference.getEntityPersister().isInstance( existing ) ) {
			throw new WrongClassException(
					"loaded object was of wrong class " + existing.getClass(),
					entityKey.getIdentifier(),
					entityReference.getEntityPersister().getEntityName()
			);
		}
		checkVersion( resultSet, context, entityKey, existing );

		// use the existing association as the hydrated state
		processingState.registerEntityInstance( existing );
		//context.registerHydratedEntity( entityReference, entityKey, existing );
		return;
	}

	// Otherwise, we need to load it from the ResultSet...

	// determine which entity instance to use.  Either the supplied one, or instantiate one
	Object entityInstance = null;
	if ( isReturn &&
			context.shouldUseOptionalEntityInformation() &&
			context.getQueryParameters().getOptionalObject() != null ) {
		final EntityKey optionalEntityKey = ResultSetProcessorHelper.getOptionalObjectKey(
				context.getQueryParameters(),
				context.getSession()
		);
		if ( optionalEntityKey != null && optionalEntityKey.equals( entityKey ) ) {
			entityInstance = context.getQueryParameters().getOptionalObject();
		}
	}

	final String concreteEntityTypeName = getConcreteEntityTypeName( resultSet, context, entityKey );
	if ( entityInstance == null ) {
		entityInstance = context.getSession().instantiate( concreteEntityTypeName, entityKey.getIdentifier() );
	}
	processingState.registerEntityInstance( entityInstance );

	// need to hydrate it.
	// grab its state from the ResultSet and keep it in the Session
	// (but don't yet initialize the object itself)
	// note that we acquire LockMode.READ even if it was not requested
	log.trace( "hydrating entity state" );
	final LockMode requestedLockMode = context.resolveLockMode( entityReference );
	final LockMode lockModeToAcquire = requestedLockMode == LockMode.NONE
			? LockMode.READ
			: requestedLockMode;

	loadFromResultSet(
			resultSet,
			context,
			entityInstance,
			concreteEntityTypeName,
			entityKey,
			lockModeToAcquire
	);
}
 
Example 7
Source File: AbstractSaveEventListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs all the actual work needed to save an entity (well to get the save moved to
 * the execution queue).
 *
 * @param entity The entity to be saved
 * @param key The id to be used for saving the entity (or null, in the case of identity columns)
 * @param persister The entity's persister instance.
 * @param useIdentityColumn Should an identity column be used for id generation?
 * @param anything Generally cascade-specific information.
 * @param source The session which is the source of the current event.
 * @param requiresImmediateIdAccess Is access to the identifier required immediately
 * after the completion of the save?  persist(), for example, does not require this...
 *
 * @return The id used to save the entity; may be null depending on the
 *         type of id generator used and the requiresImmediateIdAccess value
 */
protected Serializable performSaveOrReplicate(
		Object entity,
		EntityKey key,
		EntityPersister persister,
		boolean useIdentityColumn,
		Object anything,
		EventSource source,
		boolean requiresImmediateIdAccess) {

	Serializable id = key == null ? null : key.getIdentifier();

	boolean shouldDelayIdentityInserts = shouldDelayIdentityInserts( requiresImmediateIdAccess, source );

	// Put a placeholder in entries, so we don't recurse back and try to save() the
	// same object again. QUESTION: should this be done before onSave() is called?
	// likewise, should it be done before onUpdate()?
	EntityEntry original = source.getPersistenceContext().addEntry(
			entity,
			Status.SAVING,
			null,
			null,
			id,
			null,
			LockMode.WRITE,
			useIdentityColumn,
			persister,
			false
	);

	cascadeBeforeSave( source, persister, entity, anything );

	Object[] values = persister.getPropertyValuesToInsert( entity, getMergeMap( anything ), source );
	Type[] types = persister.getPropertyTypes();

	boolean substitute = substituteValuesIfNecessary( entity, id, values, persister, source );

	if ( persister.hasCollections() ) {
		substitute = substitute || visitCollectionsBeforeSave( entity, id, values, types, source );
	}

	if ( substitute ) {
		persister.setPropertyValues( entity, values );
	}

	TypeHelper.deepCopy(
			values,
			types,
			persister.getPropertyUpdateability(),
			values,
			source
	);

	AbstractEntityInsertAction insert = addInsertAction(
			values, id, entity, persister, useIdentityColumn, source, shouldDelayIdentityInserts
	);

	// postpone initializing id in case the insert has non-nullable transient dependencies
	// that are not resolved until cascadeAfterSave() is executed
	cascadeAfterSave( source, persister, entity, anything );
	if ( useIdentityColumn && insert.isEarlyInsert() ) {
		if ( !EntityIdentityInsertAction.class.isInstance( insert ) ) {
			throw new IllegalStateException(
					"Insert should be using an identity column, but action is of unexpected type: " +
							insert.getClass().getName()
			);
		}
		id = ((EntityIdentityInsertAction) insert).getGeneratedId();

		insert.handleNaturalIdPostSaveNotifications( id );
	}

	EntityEntry newEntry = source.getPersistenceContext().getEntry( entity );

	if ( newEntry != original ) {
		EntityEntryExtraState extraState = newEntry.getExtraState( EntityEntryExtraState.class );
		if ( extraState == null ) {
			newEntry.addExtraState( original.getExtraState( EntityEntryExtraState.class ) );
		}
	}

	return id;
}