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

The following are Jave code examples for showing how to use generateEntityKey() of the org.hibernate.engine.spi.SessionImplementor class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: BasicLazyInitializer.java   View Source Code Vote up 6 votes
private Object getReplacement() {
	final SessionImplementor session = getSession();
	if ( isUninitialized() && session != null && session.isOpen()) {
		final EntityKey key = session.generateEntityKey(
				getIdentifier(),
				session.getFactory().getEntityPersister( getEntityName() )
		);
		final Object entity = session.getPersistenceContext().getEntity(key);
		if (entity!=null) setImplementation( entity );
	}

	if ( isUninitialized() ) {
		if (replacement==null) {
			replacement = serializableProxy();
		}
		return replacement;
	}
	else {
		return getTarget();
	}

}
 
Example 2
Project: lams   File: DefaultFlushEntityEventListener.java   View Source Code Vote up 6 votes
private Object[] getDatabaseSnapshot(SessionImplementor session, EntityPersister persister, Serializable id) {
	if ( persister.isSelectBeforeUpdateRequired() ) {
		Object[] snapshot = session.getPersistenceContext()
				.getDatabaseSnapshot( id, persister );
		if ( snapshot == null ) {
			//do we even really need this? the update will fail anyway....
			if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
				session.getFactory().getStatisticsImplementor()
						.optimisticFailure( persister.getEntityName() );
			}
			throw new StaleObjectStateException( persister.getEntityName(), id );
		}
		return snapshot;
	}
	// TODO: optimize away this lookup for entities w/o unsaved-value="undefined"
	final EntityKey entityKey = session.generateEntityKey( id, persister );
	return session.getPersistenceContext().getCachedDatabaseSnapshot( entityKey );
}
 
Example 3
Project: lams   File: Loader.java   View Source Code Vote up 5 votes
private static EntityKey getOptionalObjectKey(QueryParameters queryParameters, SessionImplementor 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 4
Project: lams   File: ResultSetProcessorHelper.java   View Source Code Vote up 5 votes
public EntityKey interpretEntityKey(
		SessionImplementor 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().getEntityPersister( 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 5
Project: lams   File: AbstractEntityPersister.java   View Source Code Vote up 5 votes
/**
 * Delete an object
 */
public void delete(Serializable id, Object version, Object object, SessionImplementor 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 6
Project: lams   File: AbstractEntityTuplizer.java   View Source Code Vote up 5 votes
@Override
public void setIdentifier(Object entity, Serializable id, EntityMode entityMode, SessionImplementor 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],
					session.getFactory().getEntityPersister( 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 );
			}
			injectionValues[i] = association;
		}
		else {
			injectionValues[i] = extractedValues[i];
		}
	}
	virtualIdComponent.setPropertyValues( entity, injectionValues, entityMode );
}
 
Example 7
Project: lams   File: ManyToOneType.java   View Source Code Vote up 5 votes
/**
 * Register the entity as batch loadable, if enabled
 */
@SuppressWarnings({ "JavaDoc" })
private void scheduleBatchLoadIfNeeded(Serializable id, SessionImplementor session) throws MappingException {
	//cannot batch fetch by unique key (property-ref associations)
	if ( uniqueKeyPropertyName == null && id != null ) {
		final EntityPersister persister = getAssociatedEntityPersister( session.getFactory() );
		if ( persister.isBatchLoadable() ) {
			final EntityKey entityKey = session.generateEntityKey( id, persister );
			if ( !session.getPersistenceContext().containsEntity( entityKey ) ) {
				session.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey );
			}
		}
	}
}
 
Example 8
Project: lams   File: OneToOneType.java   View Source Code Vote up 5 votes
public boolean isNull(Object owner, SessionImplementor session) {
	if ( propertyName != null ) {
		final EntityPersister ownerPersister = session.getFactory().getEntityPersister( entityName );
		final Serializable id = session.getContextEntityIdentifier( owner );
		final EntityKey entityKey = session.generateEntityKey( id, ownerPersister );
		return session.getPersistenceContext().isPropertyNull( entityKey, getPropertyName() );
	}
	else {
		return false;
	}
}
 
Example 9
Project: lams   File: AbstractEntityPersister.java   View Source Code Vote up 4 votes
public Object[] getNaturalIdentifierSnapshot(Serializable id, SessionImplementor 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().getSettings().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( StringHelper.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.getTransactionCoordinator()
				.getJdbcCoordinator()
				.getStatementPreparer()
				.prepareStatement( sql );
		try {
			getIdentifierType().nullSafeSet( ps, id, 1, session );
			ResultSet rs = session.getTransactionCoordinator().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.getTransactionCoordinator().getJdbcCoordinator().release( rs, ps );
			}
		}
		finally {
			session.getTransactionCoordinator().getJdbcCoordinator().release( ps );
		}
	}
	catch ( SQLException e ) {
		throw getFactory().getSQLExceptionHelper().convert(
				e,
				"could not retrieve snapshot: " + MessageHelper.infoString( this, id, getFactory() ),
		        sql
		);
	}
}
 
Example 10
Project: lams   File: Collections.java   View Source Code Vote up 4 votes
private static void processDereferencedCollection(PersistentCollection coll, SessionImplementor session) {
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	final CollectionEntry entry = persistenceContext.getCollectionEntry( coll );
	final CollectionPersister loadedPersister = entry.getLoadedPersister();

	if ( loadedPersister != null && LOG.isDebugEnabled() ) {
		LOG.debugf(
				"Collection dereferenced: %s",
				MessageHelper.collectionInfoString( loadedPersister, 
						coll, entry.getLoadedKey(), session
				)
		);
	}

	// do a check
	final boolean hasOrphanDelete = loadedPersister != null && loadedPersister.hasOrphanDelete();
	if ( hasOrphanDelete ) {
		Serializable ownerId = loadedPersister.getOwnerEntityPersister().getIdentifier( coll.getOwner(), session );
		if ( ownerId == null ) {
			// the owning entity may have been deleted and its identifier unset due to
			// identifier-rollback; in which case, try to look up its identifier from
			// the persistence context
			if ( session.getFactory().getSettings().isIdentifierRollbackEnabled() ) {
				final EntityEntry ownerEntry = persistenceContext.getEntry( coll.getOwner() );
				if ( ownerEntry != null ) {
					ownerId = ownerEntry.getId();
				}
			}
			if ( ownerId == null ) {
				throw new AssertionFailure( "Unable to determine collection owner identifier for orphan-delete processing" );
			}
		}
		final EntityKey key = session.generateEntityKey( ownerId, loadedPersister.getOwnerEntityPersister() );
		final Object owner = persistenceContext.getEntity( key );
		if ( owner == null ) {
			throw new AssertionFailure(
					"collection owner not associated with session: " +
					loadedPersister.getRole()
			);
		}
		final EntityEntry e = persistenceContext.getEntry( owner );
		//only collections belonging to deleted entities are allowed to be dereferenced in the case of orphan delete
		if ( e != null && e.getStatus() != Status.DELETED && e.getStatus() != Status.GONE ) {
			throw new HibernateException(
					"A collection with cascade=\"all-delete-orphan\" was no longer referenced by the owning entity instance: " +
					loadedPersister.getRole()
			);
		}
	}

	// do the work
	entry.setCurrentPersister( null );
	entry.setCurrentKey( null );
	prepareCollectionForUpdate( coll, entry, session.getFactory() );

}
 
Example 11
Project: lams   File: AbstractLazyInitializer.java   View Source Code Vote up 4 votes
private static EntityKey generateEntityKeyOrNull(Serializable id, SessionImplementor s, String entityName) {
	if ( id == null || s == null || entityName == null ) {
		return null;
	}
	return s.generateEntityKey( id, s.getFactory().getEntityPersister( entityName ) );
}
 
Example 12
Project: lams   File: EntityIdentityInsertAction.java   View Source Code Vote up 4 votes
@Override
public void execute() throws HibernateException {
	nullifyTransientReferencesIfNotAlready();

	final EntityPersister persister = getPersister();
	final SessionImplementor session = getSession();
	final Object instance = getInstance();

	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 ) {
		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() && !veto ) {
		session.getFactory().getStatisticsImplementor().insertEntity( getPersister().getEntityName() );
	}

	markExecuted();
}