Java Code Examples for org.hibernate.pretty.MessageHelper

The following examples show how to use org.hibernate.pretty.MessageHelper. These examples are extracted from open source projects. 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 Project: lams   Source File: BatchingEntityLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected Object doBatchLoad(
		Serializable id,
		Loader loaderToUse,
		SharedSessionContractImplementor session,
		Serializable[] ids,
		Object optionalObject,
		LockOptions lockOptions) {
	if ( log.isDebugEnabled() ) {
		log.debugf( "Batch loading entity: %s", MessageHelper.infoString( persister, ids, session.getFactory() ) );
	}

	QueryParameters qp = buildQueryParameters( id, ids, optionalObject, lockOptions );

	try {
		final List results = loaderToUse.doQueryAndInitializeNonLazyCollections( session, qp, false );
		log.debug( "Done entity batch load" );
		return getObjectFromList(results, id, session);
	}
	catch ( SQLException sqle ) {
		throw session.getJdbcServices().getSqlExceptionHelper().convert(
				sqle,
				"could not load an entity batch: " + MessageHelper.infoString( persister(), ids, session.getFactory() ),
				loaderToUse.getSQLString()
		);
	}
}
 
Example 2
Source Project: lams   Source File: Loader.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Called by subclasses that batch initialize collections
 */
protected final void loadCollectionSubselect(
		final SharedSessionContractImplementor session,
		final Serializable[] ids,
		final Object[] parameterValues,
		final Type[] parameterTypes,
		final Map<String, TypedValue> namedParameters,
		final Type type) throws HibernateException {
	final Type[] idTypes = new Type[ids.length];
	Arrays.fill( idTypes, type );
	try {
		doQueryAndInitializeNonLazyCollections(
				session,
				new QueryParameters( parameterTypes, parameterValues, namedParameters, ids ),
				true
		);
	}
	catch (SQLException sqle) {
		throw factory.getJdbcServices().getSqlExceptionHelper().convert(
				sqle,
				"could not load collection by subselect: " +
						MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
				getSQLString()
		);
	}
}
 
Example 3
private void logCannotResolveNonNullableTransientDependencies(SharedSessionContractImplementor session) {
	for ( Map.Entry<Object,Set<AbstractEntityInsertAction>> entry : dependentActionsByTransientEntity.entrySet() ) {
		final Object transientEntity = entry.getKey();
		final String transientEntityName = session.guessEntityName( transientEntity );
		final Serializable transientEntityId = session.getFactory().getMetamodel().entityPersister( transientEntityName ).getIdentifier( transientEntity, session );
		final String transientEntityString = MessageHelper.infoString( transientEntityName, transientEntityId );
		final Set<String> dependentEntityStrings = new TreeSet<>();
		final Set<String> nonNullableTransientPropertyPaths = new TreeSet<>();
		for ( AbstractEntityInsertAction dependentAction : entry.getValue() ) {
			dependentEntityStrings.add( MessageHelper.infoString( dependentAction.getEntityName(), dependentAction.getId() ) );
			for ( String path : dependenciesByAction.get( dependentAction ).getNonNullableTransientPropertyPaths( transientEntity ) ) {
				final String fullPath = dependentAction.getEntityName() + '.' + path;
				nonNullableTransientPropertyPaths.add( fullPath );
			}
		}

		LOG.cannotResolveNonNullableTransientDependencies(
				transientEntityString,
				dependentEntityStrings,
				nonNullableTransientPropertyPaths
		);
	}
}
 
Example 4
Source Project: lams   Source File: SessionImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void forceFlush(EntityEntry entityEntry) throws HibernateException {
	if ( log.isDebugEnabled() ) {
		log.debugf(
				"Flushing to force deletion of re-saved object: %s",
				MessageHelper.infoString( entityEntry.getPersister(), entityEntry.getId(), getFactory() )
		);
	}

	if ( persistenceContext.getCascadeLevel() > 0 ) {
		throw new ObjectDeletedException(
				"deleted object would be re-saved by cascade (remove deleted object from associations)",
				entityEntry.getId(),
				entityEntry.getPersister().getEntityName()
		);
	}
	checkOpenOrWaitingForAutoClose();
	doFlush();
}
 
Example 5
Source Project: lams   Source File: EnabledCaching.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void evictEntityData(String entityName, Serializable identifier) {
	final EntityPersister entityDescriptor = sessionFactory.getMetamodel().entityPersister( entityName );
	final EntityDataAccess cacheAccess = entityDescriptor.getCacheAccessStrategy();
	if ( cacheAccess == null ) {
		return;
	}

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf(
				"Evicting second-level cache: %s",
				MessageHelper.infoString( entityDescriptor, identifier, sessionFactory )
		);
	}

	final Object key = cacheAccess.generateCacheKey( identifier, entityDescriptor, sessionFactory, null );
	cacheAccess.evict( key );
}
 
Example 6
Source Project: lams   Source File: EnabledCaching.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void evictCollectionData(String role, Serializable ownerIdentifier) {
	final CollectionPersister collectionDescriptor = sessionFactory.getMetamodel()
			.collectionPersister( role );

	final CollectionDataAccess cacheAccess = collectionDescriptor.getCacheAccessStrategy();
	if ( cacheAccess == null ) {
		return;
	}

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf(
				"Evicting second-level cache: %s",
				MessageHelper.collectionInfoString( collectionDescriptor, ownerIdentifier, sessionFactory )
		);
	}

	final Object key = cacheAccess.generateCacheKey( ownerIdentifier, collectionDescriptor, sessionFactory, null );
	cacheAccess.evict( key );
}
 
Example 7
/**
 * Load an instance using either the <tt>forUpdateLoader</tt> or the outer joining <tt>loader</tt>,
 * depending upon the value of the <tt>lock</tt> parameter
 */
public Object load(Serializable id, Object optionalObject, LockMode lockMode, SessionImplementor session)
		throws HibernateException {

	if ( log.isTraceEnabled() ) {
		log.trace(
				"Fetching entity: " +
				MessageHelper.infoString( this, id, getFactory() )
			);
	}

	final UniqueEntityLoader loader = getAppropriateLoader( lockMode, session );
	return loader.load( id, optionalObject, session );
}
 
Example 8
Source Project: lams   Source File: BatchingEntityLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected Object doBatchLoad(
		Serializable id,
		Loader loaderToUse,
		SharedSessionContractImplementor session,
		Serializable[] ids,
		Object optionalObject,
		LockOptions lockOptions) {
	if ( log.isDebugEnabled() ) {
		log.debugf( "Batch loading entity: %s", MessageHelper.infoString( persister, ids, session.getFactory() ) );
	}

	QueryParameters qp = buildQueryParameters( id, ids, optionalObject, lockOptions );

	try {
		final List results = loaderToUse.doQueryAndInitializeNonLazyCollections( session, qp, false );
		log.debug( "Done entity batch load" );
		// The EntityKey for any entity that is not found will remain in the batch.
		// Explicitly remove the EntityKeys for entities that were not found to
		// avoid including them in future batches that get executed.
		BatchFetchQueueHelper.removeNotFoundBatchLoadableEntityKeys(
				ids,
				results,
				persister(),
				session
		);
		return getObjectFromList(results, id, session);
	}
	catch ( SQLException sqle ) {
		throw session.getJdbcServices().getSqlExceptionHelper().convert(
				sqle,
				"could not load an entity batch: " + MessageHelper.infoString( persister(), ids, session.getFactory() ),
				loaderToUse.getSQLString()
		);
	}
}
 
Example 9
@Override
public Object load(
		Serializable id,
		Object optionalObject,
		SharedSessionContractImplementor session,
		LockOptions lockOptions) {
	final Serializable[] batch = session.getPersistenceContext()
			.getBatchFetchQueue()
			.getEntityBatch( persister(), id, maxBatchSize, persister().getEntityMode() );

	final int numberOfIds = ArrayHelper.countNonNull( batch );
	if ( numberOfIds <= 1 ) {
		final Object result =  singleKeyLoader.load( id, optionalObject, session );
		if ( result == null ) {
			// There was no entity with the specified ID. Make sure the EntityKey does not remain
			// in the batch to avoid including it in future batches that get executed.
			BatchFetchQueueHelper.removeBatchLoadableEntityKey( id, persister(), session );
		}
		return result;
	}

	final Serializable[] idsToLoad = new Serializable[numberOfIds];
	System.arraycopy( batch, 0, idsToLoad, 0, numberOfIds );

	if ( log.isDebugEnabled() ) {
		log.debugf( "Batch loading entity: %s", MessageHelper.infoString( persister(), idsToLoad, session.getFactory() ) );
	}

	QueryParameters qp = buildQueryParameters( id, idsToLoad, optionalObject, lockOptions );
	List results = dynamicLoader.doEntityBatchFetch( session, qp, idsToLoad );

	// The EntityKey for any entity that is not found will remain in the batch.
	// Explicitly remove the EntityKeys for entities that were not found to
	// avoid including them in future batches that get executed.
	BatchFetchQueueHelper.removeNotFoundBatchLoadableEntityKeys( idsToLoad, results, persister(), session );

	return getObjectFromList( results, id, session );
}
 
Example 10
@Override
public Object load(Serializable id, Object optionalObject, SharedSessionContractImplementor session, LockOptions lockOptions) {

	final Object result;
	try {
		final QueryParameters qp = new QueryParameters();
		qp.setPositionalParameterTypes( new Type[] { entityPersister.getIdentifierType() } );
		qp.setPositionalParameterValues( new Object[] { id } );
		qp.setOptionalObject( optionalObject );
		qp.setOptionalEntityName( entityPersister.getEntityName() );
		qp.setOptionalId( id );
		qp.setLockOptions( lockOptions );

		final List results = executeLoad(
				session,
				qp,
				staticLoadQuery,
				false,
				null
		);
		result = extractEntityResult( results, id );
	}
	catch ( SQLException sqle ) {
		throw session.getJdbcServices().getSqlExceptionHelper().convert(
				sqle,
				"could not load an entity: " + MessageHelper.infoString(
						entityPersister,
						id,
						entityPersister.getIdentifierType(),
						getFactory()
				),
				staticLoadQuery.getSqlStatement()
		);
	}

	log.debugf( "Done entity load : %s#%s", getEntityName(), id );
	return result;
}
 
Example 11
Source Project: cacheonix-core   Source File: Loader.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * If this is a collection initializer, we need to tell the session that a collection
 * is being initilized, to account for the possibility of the collection having
 * no elements (hence no rows in the result set).
 */
private void handleEmptyCollections(
        final Serializable[] keys,
        final Object resultSetId,
        final SessionImplementor session) {

	if ( keys != null ) {
		// this is a collection initializer, so we must create a collection
		// for each of the passed-in keys, to account for the possibility
		// that the collection is empty and has no rows in the result set

		CollectionPersister[] collectionPersisters = getCollectionPersisters();
		for ( int j=0; j<collectionPersisters.length; j++ ) {
			for ( int i = 0; i < keys.length; i++ ) {
				//handle empty collections

				if ( log.isDebugEnabled() ) {
					log.debug( 
							"result set contains (possibly empty) collection: " +
							MessageHelper.collectionInfoString( collectionPersisters[j], keys[i], getFactory() ) 
						);
				}

				session.getPersistenceContext()
						.getLoadContexts()
						.getCollectionLoadContext( ( ResultSet ) resultSetId )
						.getLoadingCollection( collectionPersisters[j], keys[i] );
			}
		}
	}

	// else this is not a collection initializer (and empty collections will
	// be detected by looking for the owner's identifier in the result set)
}
 
Example 12
Source Project: lams   Source File: Loader.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * If this is a collection initializer, we need to tell the session that a collection
 * is being initialized, to account for the possibility of the collection having
 * no elements (hence no rows in the result set).
 */
private void handleEmptyCollections(
		final Serializable[] keys,
		final Object resultSetId,
		final SharedSessionContractImplementor session) {

	if ( keys != null ) {
		final boolean debugEnabled = LOG.isDebugEnabled();
		// this is a collection initializer, so we must create a collection
		// for each of the passed-in keys, to account for the possibility
		// that the collection is empty and has no rows in the result set
		CollectionPersister[] collectionPersisters = getCollectionPersisters();
		for ( CollectionPersister collectionPersister : collectionPersisters ) {
			for ( Serializable key : keys ) {
				//handle empty collections
				if ( debugEnabled ) {
					LOG.debugf(
							"Result set contains (possibly empty) collection: %s",
							MessageHelper.collectionInfoString( collectionPersister, key, getFactory() )
					);
				}

				session.getPersistenceContext()
						.getLoadContexts()
						.getCollectionLoadContext( (ResultSet) resultSetId )
						.getLoadingCollection( collectionPersister, key );
			}
		}
	}

	// else this is not a collection initializer (and empty collections will
	// be detected by looking for the owner's identifier in the result set)
}
 
Example 13
public void preFlush(PersistentCollection collection) throws HibernateException {
	
	boolean nonMutableChange = collection.isDirty() && 
			getLoadedPersister()!=null && 
			!getLoadedPersister().isMutable();
	if (nonMutableChange) {
		throw new HibernateException(
				"changed an immutable collection instance: " + 
				MessageHelper.collectionInfoString( getLoadedPersister().getRole(), getLoadedKey() )
			);
	}
	
	dirty(collection);
	
	if ( log.isDebugEnabled() && collection.isDirty() && getLoadedPersister() != null ) {
		log.debug(
				"Collection dirty: " +
				MessageHelper.collectionInfoString( getLoadedPersister().getRole(), getLoadedKey() )
			);
	}

	setDoupdate(false);
	setDoremove(false);
	setDorecreate(false);
	setReached(false);
	setProcessed(false);
}
 
Example 14
private void evictCollection(PersistentCollection collection) {
	CollectionEntry ce = (CollectionEntry) getSession().getPersistenceContext().getCollectionEntries().remove(collection);
	if ( log.isDebugEnabled() )
		log.debug(
				"evicting collection: " +
				MessageHelper.collectionInfoString( ce.getLoadedPersister(), ce.getLoadedKey(), getSession().getFactory() )
		);
	if ( ce.getLoadedPersister() != null && ce.getLoadedKey() != null ) {
		//TODO: is this 100% correct?
		getSession().getPersistenceContext().getCollectionsByKey().remove( 
				new CollectionKey( ce.getLoadedPersister(), ce.getLoadedKey(), getSession().getEntityMode() ) 
		);
	}
}
 
Example 15
public void evict(Class persistentClass, Serializable id) throws HibernateException {
	EntityPersister p = getEntityPersister( persistentClass.getName() );
	if ( p.hasCache() ) {
		if ( log.isDebugEnabled() ) {
			log.debug( "evicting second-level cache: " + MessageHelper.infoString(p, id, this) );
		}
		CacheKey cacheKey = new CacheKey( id, p.getIdentifierType(), p.getRootEntityName(), EntityMode.POJO, this );
		p.getCache().remove( cacheKey );
	}
}
 
Example 16
/**
 * Load the data for the object with the specified id into a newly created object.
 * This is only called when lazily initializing a proxy.
 * Do NOT return a proxy.
 */
public Object immediateLoad(String entityName, Serializable id) throws HibernateException {
	if ( log.isDebugEnabled() ) {
		EntityPersister persister = getFactory().getEntityPersister(entityName);
		log.debug( "initializing proxy: " + MessageHelper.infoString( persister, id, getFactory() ) );
	}
	
	LoadEvent event = new LoadEvent(id, entityName, true, this);
	fireLoad(event, LoadEventListener.IMMEDIATE_LOAD);
	return event.getResult();
}
 
Example 17
public Object getElementByIndex(Serializable key, Object index, SessionImplementor session, Object owner) {
	try {
		PreparedStatement st = session.getBatcher().prepareSelectStatement(sqlSelectRowByIndexString);
		try {
			getKeyType().nullSafeSet(st, key, 1, session);
			getIndexType().nullSafeSet( st, incrementIndexByBase(index), keyColumnNames.length + 1, session );
			ResultSet rs = st.executeQuery();
			try {
				if ( rs.next() ) {
					return getElementType().nullSafeGet(rs, elementColumnAliases, session, owner);
				}
				else {
					return null;
				}
			}
			finally {
				rs.close();
			}
		}
		finally {
			session.getBatcher().closeStatement( st );
		}
	}
	catch (SQLException sqle) {
		throw JDBCExceptionHelper.convert(
				getFactory().getSQLExceptionConverter(),
				sqle,
				"could not read row: " + 
				MessageHelper.collectionInfoString( this, key, getFactory() ),
				sqlSelectSizeString
			);
	}
}
 
Example 18
/**
 * Marshall the fields of a persistent instance to a prepared statement
 */
protected int dehydrate(
		final Serializable id,
        final Object[] fields,
        final Object rowId,
        final boolean[] includeProperty,
        final boolean[][] includeColumns,
        final int j,
        final PreparedStatement ps,
        final SessionImplementor session,
        int index) throws SQLException, HibernateException {

	if ( log.isTraceEnabled() ) {
		log.trace( "Dehydrating entity: " + MessageHelper.infoString( this, id, getFactory() ) );
	}

	for ( int i = 0; i < entityMetamodel.getPropertySpan(); i++ ) {
		if ( includeProperty[i] && isPropertyOfTable( i, j ) ) {
			getPropertyTypes()[i].nullSafeSet( ps, fields[i], index, includeColumns[i], session );
			//index += getPropertyColumnSpan( i );
			index += ArrayHelper.countTrue( includeColumns[i] ); //TODO:  this is kinda slow...
		}
	}

	if ( rowId != null ) {
		ps.setObject( index, rowId );
		index += 1;
	}
	else if ( id != null ) {
		getIdentifierType().nullSafeSet( ps, id, index, session );
		index += getIdentifierColumnSpan();
	}

	return index;

}
 
Example 19
private boolean exists(Serializable key, Object indexOrElement, Type indexOrElementType, String sql, SharedSessionContractImplementor session) {
	try {
		PreparedStatement st = session
				.getJdbcCoordinator()
				.getStatementPreparer()
				.prepareStatement( sql );
		try {
			getKeyType().nullSafeSet( st, key, 1, session );
			indexOrElementType.nullSafeSet( st, indexOrElement, keyColumnNames.length + 1, session );
			ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st );
			try {
				return rs.next();
			}
			finally {
				session.getJdbcCoordinator().getResourceRegistry().release( rs, st );
			}
		}
		catch ( TransientObjectException e ) {
			return false;
		}
		finally {
			session.getJdbcCoordinator().getResourceRegistry().release( st );
			session.getJdbcCoordinator().afterStatementExecution();
		}
	}
	catch ( SQLException sqle ) {
		throw getSQLExceptionHelper().convert(
				sqle,
				"could not check row existence: " +
						MessageHelper.collectionInfoString( this, key, getFactory() ),
				sqlSelectSizeString
		);
	}
}
 
Example 20
public int getSize(Serializable key, SessionImplementor session) {
	try {
		PreparedStatement st = session.getBatcher().prepareSelectStatement(sqlSelectSizeString);
		try {
			getKeyType().nullSafeSet(st, key, 1, session);
			ResultSet rs = st.executeQuery();
			try {
				return rs.next() ? rs.getInt(1) - baseIndex : 0;
			}
			finally {
				rs.close();
			}
		}
		finally {
			session.getBatcher().closeStatement( st );
		}
	}
	catch (SQLException sqle) {
		throw JDBCExceptionHelper.convert(
				getFactory().getSQLExceptionConverter(),
				sqle,
				"could not retrieve collection size: " + 
				MessageHelper.collectionInfoString( this, key, getFactory() ),
				sqlSelectSizeString
			);
	}
}
 
Example 21
Source Project: lams   Source File: CollectionEntry.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void preFlush(PersistentCollection collection) throws HibernateException {
	if ( loadedKey == null && collection.getKey() != null ) {
		loadedKey = collection.getKey();
	}

	boolean nonMutableChange = collection.isDirty()
			&& getLoadedPersister() != null
			&& !getLoadedPersister().isMutable();
	if ( nonMutableChange ) {
		throw new HibernateException(
				"changed an immutable collection instance: " +
				MessageHelper.collectionInfoString( getLoadedPersister().getRole(), getLoadedKey() )
		);
	}

	dirty( collection );

	if ( LOG.isDebugEnabled() && collection.isDirty() && getLoadedPersister() != null ) {
		LOG.debugf(
				"Collection dirty: %s",
				MessageHelper.collectionInfoString( getLoadedPersister().getRole(), getLoadedKey() )
		);
	}

	setReached( false );
	setProcessed( false );

	setDoupdate( false );
	setDoremove( false );
	setDorecreate( false );
}
 
Example 22
@Override
public Object[] getCachedDatabaseSnapshot(EntityKey key) {
	final Object snapshot = entitySnapshotsByKey.get( key );
	if ( snapshot == NO_ROW ) {
		throw new IllegalStateException(
				"persistence context reported no row snapshot for "
						+ MessageHelper.infoString( key.getEntityName(), key.getIdentifier() )
		);
	}
	return (Object[]) snapshot;
}
 
Example 23
Source Project: lams   Source File: LoadContexts.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attempt to locate the loading collection given the owner's key.  The lookup here
 * occurs against all result-set contexts...
 *
 * @param persister The collection persister
 * @param ownerKey The owner key
 * @return The loading collection, or null if not found.
 */
public PersistentCollection locateLoadingCollection(CollectionPersister persister, Serializable ownerKey) {
	final LoadingCollectionEntry lce = locateLoadingCollectionEntry( new CollectionKey( persister, ownerKey ) );
	if ( lce != null ) {
		if ( LOG.isTraceEnabled() ) {
			LOG.tracef(
					"Returning loading collection: %s",
					MessageHelper.collectionInfoString( persister, ownerKey, getSession().getFactory() )
			);
		}
		return lce.getCollection();
	}
	return null;
}
 
Example 24
/**
 * 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 25
/**
 * Perfoms the load of an entity.
 *
 * @return The loaded entity.
 * @throws HibernateException
 */
protected Object load(
	final LoadEvent event, 
	final EntityPersister persister, 
	final EntityKey keyToLoad, 
	final LoadEventListener.LoadType options)
throws HibernateException {

	if ( event.getInstanceToLoad() != null ) {
		if ( event.getSession().getPersistenceContext().getEntry( event.getInstanceToLoad() ) != null ) {
			throw new PersistentObjectException(
					"attempted to load into an instance that was already associated with the session: " +
					MessageHelper.infoString( persister, event.getEntityId(), event.getSession().getFactory() )
				);
		}
		persister.setIdentifier( event.getInstanceToLoad(), event.getEntityId(), event.getSession().getEntityMode() );
	}

	Object entity = doLoad(event, persister, keyToLoad, options);
	
	boolean isOptionalInstance = event.getInstanceToLoad() != null;
	
	if ( !options.isAllowNulls() || isOptionalInstance ) {
		if ( entity == null ) {
			event.getSession().getFactory().getEntityNotFoundDelegate().handleEntityNotFound( event.getEntityClassName(), event.getEntityId() );
		}
	}

	if ( isOptionalInstance && entity != event.getInstanceToLoad() ) {
		throw new NonUniqueObjectException( event.getEntityId(), event.getEntityClassName() );
	}

	return entity;
}
 
Example 26
Source Project: cacheonix-core   Source File: Loader.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Called by subclasses that batch initialize collections
 */
protected final void loadCollectionSubselect(
        final SessionImplementor session,
        final Serializable[] ids,
        final Object[] parameterValues,
        final Type[] parameterTypes,
        final Map namedParameters,
        final Type type) throws HibernateException {

	Type[] idTypes = new Type[ids.length];
	Arrays.fill( idTypes, type );
	try {
		doQueryAndInitializeNonLazyCollections( session,
				new QueryParameters( parameterTypes, parameterValues, namedParameters, ids ),
				true 
			);
	}
	catch ( SQLException sqle ) {
		throw JDBCExceptionHelper.convert(
		        factory.getSQLExceptionConverter(),
		        sqle,
		        "could not load collection by subselect: " + 
		        MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
		        getSQLString()
			);
	}
}
 
Example 27
/**
 * Coordinates the efforts to load a given entity. First, an attempt is
 * made to load the entity from the session-level cache. If not found there,
 * an attempt is made to locate it in second-level cache. Lastly, an
 * attempt is made to load it directly from the datasource.
 *
 * @param event The load event
 *
 * @return The loaded entity, or null.
 */
protected Serializable resolveNaturalId(final ResolveNaturalIdEvent event) {
	final EntityPersister persister = event.getEntityPersister();

	final boolean traceEnabled = LOG.isTraceEnabled();
	if ( traceEnabled ) {
		LOG.tracev(
				"Attempting to resolve: {0}#{1}",
				MessageHelper.infoString( persister ),
				event.getNaturalIdValues()
		);
	}

	Serializable entityId = resolveFromCache( event );
	if ( entityId != null ) {
		if ( traceEnabled ) {
			LOG.tracev(
					"Resolved object in cache: {0}#{1}",
					MessageHelper.infoString( persister ),
					event.getNaturalIdValues()
			);
		}
		return entityId;
	}

	if ( traceEnabled ) {
		LOG.tracev(
				"Object not resolved in any cache: {0}#{1}",
				MessageHelper.infoString( persister ),
				event.getNaturalIdValues()
		);
	}

	return loadFromDatasource( event );
}
 
Example 28
public void evictCollection(String roleName, Serializable id) throws HibernateException {
	CollectionPersister p = getCollectionPersister(roleName);
	if ( p.hasCache() ) {
		if ( log.isDebugEnabled() ) {
			log.debug( "evicting second-level cache: " + MessageHelper.collectionInfoString(p, id, this) );
		}
		CacheKey cacheKey = new CacheKey( id, p.getKeyType(), p.getRole(), EntityMode.POJO, this );
		p.getCache().remove( cacheKey );
	}
}
 
Example 29
Source Project: cacheonix-core   Source File: Loader.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Called by wrappers that batch initialize collections
 */
public final void loadCollectionBatch(
        final SessionImplementor session,
        final Serializable[] ids,
        final Type type) throws HibernateException {

	if ( log.isDebugEnabled() ) {
		log.debug( 
				"batch loading collection: "+ 
				MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() )
			);
	}

	Type[] idTypes = new Type[ids.length];
	Arrays.fill( idTypes, type );
	try {
		doQueryAndInitializeNonLazyCollections( 
				session,
				new QueryParameters( idTypes, ids, ids ),
				true 
			);
	}
	catch ( SQLException sqle ) {
		throw JDBCExceptionHelper.convert(
		        factory.getSQLExceptionConverter(),
		        sqle,
		        "could not initialize a collection batch: " + 
		        MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
		        getSQLString()
			);
	}
	
	log.debug("done batch load");

}
 
Example 30
private void performReplication(
		Object entity,
		Serializable id,
		Object version,
		EntityPersister persister,
		ReplicationMode replicationMode,
		EventSource source) throws HibernateException {

	if ( LOG.isTraceEnabled() ) {
		LOG.tracev( "Replicating changes to {0}", MessageHelper.infoString( persister, id, source.getFactory() ) );
	}

	new OnReplicateVisitor( source, id, entity, true ).process( entity, persister );

	source.getPersistenceContext().addEntity(
			entity,
			( persister.isMutable() ? Status.MANAGED : Status.READ_ONLY ),
			null,
			source.generateEntityKey( id, persister ),
			version,
			LockMode.NONE,
			true,
			persister,
			true
	);

	cascadeAfterReplicate( entity, persister, replicationMode, source );
}