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

The following examples show how to use org.hibernate.engine.spi.SharedSessionContractImplementor#generateEntityKey() . 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 6 votes vote down vote up
private static EntityKey getOptionalObjectKey(QueryParameters queryParameters, SharedSessionContractImplementor session) {
	final Object optionalObject = queryParameters.getOptionalObject();
	final Serializable optionalId = queryParameters.getOptionalId();
	final String optionalEntityName = queryParameters.getOptionalEntityName();

	if ( optionalObject != null && optionalEntityName != null ) {
		return session.generateEntityKey(
				optionalId, session.getEntityPersister(
						optionalEntityName,
						optionalObject
				)
		);
	}
	else {
		return null;
	}

}
 
Example 2
Source File: ResultSetProcessorHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public EntityKey interpretEntityKey(
		SharedSessionContractImplementor session,
		String optionalEntityName,
		Serializable optionalId,
		Object optionalObject) {
	if ( optionalEntityName != null ) {
		final EntityPersister entityPersister;
		if ( optionalObject != null ) {
			entityPersister = session.getEntityPersister( optionalEntityName, optionalObject );
		}
		else {
			entityPersister = session.getFactory().getMetamodel().entityPersister( optionalEntityName );
		}
		if ( entityPersister.isInstance( optionalId )
				&& !entityPersister.getEntityMetamodel().getIdentifierProperty().isVirtual()
				&& entityPersister.getEntityMetamodel().getIdentifierProperty().isEmbedded() ) {
			// non-encapsulated composite identifier
			final Serializable identifierState = ((CompositeType) entityPersister.getIdentifierType()).getPropertyValues(
					optionalId,
					session
			);
			return session.generateEntityKey( identifierState, entityPersister );
		}
		else {
			return session.generateEntityKey( optionalId, entityPersister );
		}
	}
	else {
		return null;
	}
}
 
Example 3
Source File: AbstractEntityPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Delete an object
 */
public void delete(Serializable id, Object version, Object object, SharedSessionContractImplementor session)
		throws HibernateException {
	final int span = getTableSpan();
	boolean isImpliedOptimisticLocking = !entityMetamodel.isVersioned() && isAllOrDirtyOptLocking();
	Object[] loadedState = null;
	if ( isImpliedOptimisticLocking ) {
		// need to treat this as if it where optimistic-lock="all" (dirty does *not* make sense);
		// first we need to locate the "loaded" state
		//
		// Note, it potentially could be a proxy, so doAfterTransactionCompletion the location the safe way...
		final EntityKey key = session.generateEntityKey( id, this );
		Object entity = session.getPersistenceContext().getEntity( key );
		if ( entity != null ) {
			EntityEntry entry = session.getPersistenceContext().getEntry( entity );
			loadedState = entry.getLoadedState();
		}
	}

	final String[] deleteStrings;
	if ( isImpliedOptimisticLocking && loadedState != null ) {
		// we need to utilize dynamic delete statements
		deleteStrings = generateSQLDeletStrings( loadedState );
	}
	else {
		// otherwise, utilize the static delete statements
		deleteStrings = getSQLDeleteStrings();
	}

	for ( int j = span - 1; j >= 0; j-- ) {
		delete( id, version, j, object, deleteStrings[j], session, loadedState );
	}

}
 
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: BatchFetchQueueHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Remove the entity key with the specified {@code id} and {@code persister} from
 * the batch loadable entities {@link BatchFetchQueue}.
 *
 * @param id - the ID for the entity to be removed
 * @param persister - the entity persister
 * @param session - the session
 */
public static void removeBatchLoadableEntityKey(
		Serializable id,
		EntityPersister persister,
		SharedSessionContractImplementor session) {
	final EntityKey entityKey = session.generateEntityKey( id, persister );
	final BatchFetchQueue batchFetchQueue = session.getPersistenceContext().getBatchFetchQueue();
	batchFetchQueue.removeBatchLoadableEntityKey( entityKey );
}
 
Example 6
Source File: OneToOneType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isNull(Object owner, SharedSessionContractImplementor session) {
	if ( propertyName != null ) {
		final EntityPersister ownerPersister = session.getFactory().getMetamodel().entityPersister( entityName );
		final Serializable id = session.getContextEntityIdentifier( owner );
		final EntityKey entityKey = session.generateEntityKey( id, ownerPersister );
		return session.getPersistenceContext().isPropertyNull( entityKey, getPropertyName() );
	}
	else {
		return false;
	}
}
 
Example 7
Source File: ReactiveAbstractEntityPersister.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
default CompletionStage<?> deleteReactive(
		Serializable id, Object version, Object object,
		SharedSessionContractImplementor session)
		throws HibernateException {
	final int span = delegate().getTableSpan();
	boolean isImpliedOptimisticLocking = !delegate().getEntityMetamodel().isVersioned() && isAllOrDirtyOptimisticLocking();
	Object[] loadedState = null;
	if ( isImpliedOptimisticLocking ) {
		// need to treat this as if it where optimistic-lock="all" (dirty does *not* make sense);
		// first we need to locate the "loaded" state
		//
		// Note, it potentially could be a proxy, so doAfterTransactionCompletion the location the safe way...
		final EntityKey key = session.generateEntityKey( id, delegate());
		final PersistenceContext persistenceContext = session.getPersistenceContextInternal();
		Object entity = persistenceContext.getEntity( key );
		if ( entity != null ) {
			EntityEntry entry = persistenceContext.getEntry( entity );
			loadedState = entry.getLoadedState();
		}
	}

	final String[] deleteStrings;
	if ( isImpliedOptimisticLocking && loadedState != null ) {
		// we need to utilize dynamic delete statements
		deleteStrings = generateSQLDeleteStrings( loadedState );
	}
	else {
		// otherwise, utilize the static delete statements
		deleteStrings = delegate().getSQLDeleteStrings();
	}

	CompletionStage<?> deleteStage = CompletionStages.nullFuture();
	for ( int j = span - 1; j >= 0; j-- ) {
		// For now we assume there is only one delete query
		int jj = j;
		Object[] state = loadedState;
		deleteStage = deleteStage.thenCompose(
				v-> deleteReactive(
						id,
						version,
						jj,
						object,
						deleteStrings[jj],
						session,
						state
				));
	}

	return deleteStage;
}
 
Example 8
Source File: AbstractEntityPersister.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public Object[] getNaturalIdentifierSnapshot(Serializable id, SharedSessionContractImplementor session)
		throws HibernateException {
	if ( !hasNaturalIdentifier() ) {
		throw new MappingException(
				"persistent class did not define a natural-id : " + MessageHelper.infoString(
						this
				)
		);
	}
	if ( LOG.isTraceEnabled() ) {
		LOG.tracev(
				"Getting current natural-id snapshot state for: {0}",
				MessageHelper.infoString( this, id, getFactory() )
		);
	}

	int[] naturalIdPropertyIndexes = getNaturalIdentifierProperties();
	int naturalIdPropertyCount = naturalIdPropertyIndexes.length;
	boolean[] naturalIdMarkers = new boolean[getPropertySpan()];
	Type[] extractionTypes = new Type[naturalIdPropertyCount];
	for ( int i = 0; i < naturalIdPropertyCount; i++ ) {
		extractionTypes[i] = getPropertyTypes()[naturalIdPropertyIndexes[i]];
		naturalIdMarkers[naturalIdPropertyIndexes[i]] = true;
	}

	///////////////////////////////////////////////////////////////////////
	// TODO : look at perhaps caching this...
	Select select = new Select( getFactory().getDialect() );
	if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
		select.setComment( "get current natural-id state " + getEntityName() );
	}
	select.setSelectClause( concretePropertySelectFragmentSansLeadingComma( getRootAlias(), naturalIdMarkers ) );
	select.setFromClause( fromTableFragment( getRootAlias() ) + fromJoinFragment( getRootAlias(), true, false ) );

	String[] aliasedIdColumns = StringHelper.qualify( getRootAlias(), getIdentifierColumnNames() );
	String whereClause = new StringBuilder()
			.append(
					String.join(
							"=? and ",
							aliasedIdColumns
					)
			)
			.append( "=?" )
			.append( whereJoinFragment( getRootAlias(), true, false ) )
			.toString();

	String sql = select.setOuterJoins( "", "" )
			.setWhereClause( whereClause )
			.toStatementString();
	///////////////////////////////////////////////////////////////////////

	Object[] snapshot = new Object[naturalIdPropertyCount];
	try {
		PreparedStatement ps = session
				.getJdbcCoordinator()
				.getStatementPreparer()
				.prepareStatement( sql );
		try {
			getIdentifierType().nullSafeSet( ps, id, 1, session );
			ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( ps );
			try {
				//if there is no resulting row, return null
				if ( !rs.next() ) {
					return null;
				}
				final EntityKey key = session.generateEntityKey( id, this );
				Object owner = session.getPersistenceContext().getEntity( key );
				for ( int i = 0; i < naturalIdPropertyCount; i++ ) {
					snapshot[i] = extractionTypes[i].hydrate(
							rs, getPropertyAliases(
									"",
									naturalIdPropertyIndexes[i]
							), session, null
					);
					if ( extractionTypes[i].isEntityType() ) {
						snapshot[i] = extractionTypes[i].resolve( snapshot[i], session, owner );
					}
				}
				return snapshot;
			}
			finally {
				session.getJdbcCoordinator().getResourceRegistry().release( rs, ps );
			}
		}
		finally {
			session.getJdbcCoordinator().getResourceRegistry().release( ps );
			session.getJdbcCoordinator().afterStatementExecution();
		}
	}
	catch (SQLException e) {
		throw getFactory().getSQLExceptionHelper().convert(
				e,
				"could not retrieve snapshot: " + MessageHelper.infoString( this, id, getFactory() ),
				sql
		);
	}
}
 
Example 9
Source File: AbstractLazyInitializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private static EntityKey generateEntityKeyOrNull(Serializable id, SharedSessionContractImplementor s, String entityName) {
	if ( id == null || s == null || entityName == null ) {
		return null;
	}
	return s.generateEntityKey( id, s.getFactory().getEntityPersister( entityName ) );
}
 
Example 10
Source File: EntityIdentityInsertAction.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();

	setVeto( preInsert() );

	// Don't need to lock the cache here, since if someone
	// else inserted the same pk first, the insert would fail

	if ( !isVeto() ) {
		generatedId = persister.insert( getState(), instance, session );
		if ( persister.hasInsertGeneratedProperties() ) {
			persister.processInsertGeneratedProperties( generatedId, instance, getState(), session );
		}
		//need to do that here rather than in the save event listener to let
		//the post insert events to have a id-filled entity when IDENTITY is used (EJB3)
		persister.setIdentifier( instance, generatedId, session );
		session.getPersistenceContext().registerInsertedKey( getPersister(), generatedId );
		entityKey = session.generateEntityKey( generatedId, persister );
		session.getPersistenceContext().checkUniqueness( entityKey, getInstance() );
	}


	//TODO: this bit actually has to be called after all cascades!
	//      but since identity insert is called *synchronously*,
	//      instead of asynchronously as other actions, it isn't
	/*if ( persister.hasCache() && !persister.isCacheInvalidationRequired() ) {
		cacheEntry = new CacheEntry(object, persister, session);
		persister.getCache().insert(generatedId, cacheEntry);
	}*/

	postInsert();

	if ( session.getFactory().getStatistics().isStatisticsEnabled() && !isVeto() ) {
		session.getFactory().getStatistics().insertEntity( getPersister().getEntityName() );
	}

	markExecuted();
}