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

The following are Jave code examples for showing how to use getFactory() 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: BasicCollectionPersister.java   View Source Code Vote up 5 votes
@Override
   protected CollectionInitializer createSubselectInitializer(SubselectFetch subselect, SessionImplementor session) {
	return new SubselectCollectionLoader( 
			this,
			subselect.toSubselectString( getCollectionType().getLHSPropertyName() ),
			subselect.getResult(),
			subselect.getQueryParameters(),
			subselect.getNamedParameterLocMap(),
			session.getFactory(),
			session.getLoadQueryInfluencers() 
	);
}
 
Example 2
Project: lams   File: OneToManyPersister.java   View Source Code Vote up 5 votes
@Override
   protected CollectionInitializer createSubselectInitializer(SubselectFetch subselect, SessionImplementor session) {
	return new SubselectOneToManyLoader( 
			this,
			subselect.toSubselectString( getCollectionType().getLHSPropertyName() ),
			subselect.getResult(),
			subselect.getQueryParameters(),
			subselect.getNamedParameterLocMap(),
			session.getFactory(),
			session.getLoadQueryInfluencers()
		);
}
 
Example 3
Project: lams   File: NaturalIdCacheKey.java   View Source Code Vote up 5 votes
/**
 * Construct a new key for a caching natural identifier resolutions into the second level cache.
 * Note that an entity name should always be the root entity name, not a subclass entity name.
 *
 * @param naturalIdValues The naturalIdValues associated with the cached data
 * @param persister The persister for the entity
 * @param session The originating session
 */
public NaturalIdCacheKey(
		final Object[] naturalIdValues,
		final EntityPersister persister,
		final SessionImplementor session) {

	this.entityName = persister.getRootEntityName();
	this.tenantId = session.getTenantIdentifier();

	this.naturalIdValues = new Serializable[naturalIdValues.length];

	final SessionFactoryImplementor factory = session.getFactory();
	final int[] naturalIdPropertyIndexes = persister.getNaturalIdentifierProperties();
	final Type[] propertyTypes = persister.getPropertyTypes();

	final int prime = 31;
	int result = 1;
	result = prime * result + ( ( this.entityName == null ) ? 0 : this.entityName.hashCode() );
	result = prime * result + ( ( this.tenantId == null ) ? 0 : this.tenantId.hashCode() );
	for ( int i = 0; i < naturalIdValues.length; i++ ) {
		final int naturalIdPropertyIndex = naturalIdPropertyIndexes[i];
		final Type type = propertyTypes[naturalIdPropertyIndex];
		final Object value = naturalIdValues[i];

		result = prime * result + (value != null ? type.getHashCode( value, factory ) : 0);

		// The natural id may not be fully resolved in some situations.  See HHH-7513 for one of them
		// (re-attaching a mutable natural id uses a database snapshot and hydration does not resolve associations).
		// TODO: The snapshot should probably be revisited at some point.  Consider semi-resolving, hydrating, etc.
		if (type instanceof EntityType && type.getSemiResolvedType( factory ).getReturnedClass().isInstance( value )) {
			this.naturalIdValues[i] = (Serializable) value;
		}
		else {
			this.naturalIdValues[i] = type.disassemble( value, session, null );
		}
	}

	this.hashCode = result;
	initTransients();
}
 
Example 4
Project: lams   File: OutputsImpl.java   View Source Code Vote up 5 votes
public CustomLoaderExtension(
		CustomQuery customQuery,
		QueryParameters queryParameters,
		SessionImplementor session) {
	super( customQuery, session.getFactory() );
	this.queryParameters = queryParameters;
	this.session = session;
}
 
Example 5
Project: lams   File: BulkOperationCleanupAction.java   View Source Code Vote up 5 votes
/**
 * Constructs an action to cleanup "affected cache regions" based on the
 * affected entity persisters.  The affected regions are defined as the
 * region (if any) of the entity persisters themselves, plus the
 * collection regions for any collection in which those entity
 * persisters participate as elements/keys/etc.
 *
 * @param session The session to which this request is tied.
 * @param affectedQueryables The affected entity persisters.
 */
public BulkOperationCleanupAction(SessionImplementor session, Queryable... affectedQueryables) {
	final SessionFactoryImplementor factory = session.getFactory();
	final LinkedHashSet<String> spacesList = new LinkedHashSet<String>();
	for ( Queryable persister : affectedQueryables ) {
		spacesList.addAll( Arrays.asList( (String[]) persister.getQuerySpaces() ) );

		if ( persister.hasCache() ) {
			entityCleanups.add( new EntityCleanup( persister.getCacheAccessStrategy() ) );
		}
		if ( persister.hasNaturalIdentifier() && persister.hasNaturalIdCache() ) {
			naturalIdCleanups.add( new NaturalIdCleanup( persister.getNaturalIdCacheAccessStrategy() ) );
		}

		final Set<String> roles = factory.getCollectionRolesByEntityParticipant( persister.getEntityName() );
		if ( roles != null ) {
			for ( String role : roles ) {
				final CollectionPersister collectionPersister = factory.getCollectionPersister( role );
				if ( collectionPersister.hasCache() ) {
					collectionCleanups.add( new CollectionCleanup( collectionPersister.getCacheAccessStrategy() ) );
				}
			}
		}
	}

	this.affectedTableSpaces = spacesList.toArray( new String[ spacesList.size() ] );
}
 
Example 6
Project: lams   File: BulkOperationCleanupAction.java   View Source Code Vote up 5 votes
/**
 * Constructs an action to cleanup "affected cache regions" based on a
 * set of affected table spaces.  This differs from {@link #BulkOperationCleanupAction(SessionImplementor, Queryable[])}
 * in that here we have the affected <strong>table names</strong>.  From those
 * we deduce the entity persisters which are affected based on the defined
 * {@link EntityPersister#getQuerySpaces() table spaces}; and from there, we
 * determine the affected collection regions based on any collections
 * in which those entity persisters participate as elements/keys/etc.
 *
 * @param session The session to which this request is tied.
 * @param tableSpaces The table spaces.
 */
@SuppressWarnings({ "unchecked" })
public BulkOperationCleanupAction(SessionImplementor session, Set tableSpaces) {
	final LinkedHashSet<String> spacesList = new LinkedHashSet<String>();
	spacesList.addAll( tableSpaces );

	final SessionFactoryImplementor factory = session.getFactory();
	for ( String entityName : factory.getAllClassMetadata().keySet() ) {
		final EntityPersister persister = factory.getEntityPersister( entityName );
		final String[] entitySpaces = (String[]) persister.getQuerySpaces();
		if ( affectedEntity( tableSpaces, entitySpaces ) ) {
			spacesList.addAll( Arrays.asList( entitySpaces ) );

			if ( persister.hasCache() ) {
				entityCleanups.add( new EntityCleanup( persister.getCacheAccessStrategy() ) );
			}
			if ( persister.hasNaturalIdentifier() && persister.hasNaturalIdCache() ) {
				naturalIdCleanups.add( new NaturalIdCleanup( persister.getNaturalIdCacheAccessStrategy() ) );
			}

			final Set<String> roles = session.getFactory().getCollectionRolesByEntityParticipant( persister.getEntityName() );
			if ( roles != null ) {
				for ( String role : roles ) {
					final CollectionPersister collectionPersister = factory.getCollectionPersister( role );
					if ( collectionPersister.hasCache() ) {
						collectionCleanups.add(
								new CollectionCleanup( collectionPersister.getCacheAccessStrategy() )
						);
					}
				}
			}
		}
	}

	this.affectedTableSpaces = spacesList.toArray( new String[ spacesList.size() ] );
}
 
Example 7
Project: lams   File: EntityType.java   View Source Code Vote up 5 votes
/**
 * Load an instance by a unique key that is not the primary key.
 *
 * @param entityName The name of the entity to load
 * @param uniqueKeyPropertyName The name of the property defining the uniqie key.
 * @param key The unique key property value.
 * @param session The originating session.
 * @return The loaded entity
 * @throws HibernateException generally indicates problems performing the load.
 */
public Object loadByUniqueKey(
		String entityName, 
		String uniqueKeyPropertyName, 
		Object key, 
		SessionImplementor session) throws HibernateException {
	final SessionFactoryImplementor factory = session.getFactory();
	UniqueKeyLoadable persister = ( UniqueKeyLoadable ) factory.getEntityPersister( entityName );

	//TODO: implement caching?! proxies?!

	EntityUniqueKey euk = new EntityUniqueKey(
			entityName, 
			uniqueKeyPropertyName, 
			key, 
			getIdentifierOrUniqueKeyType( factory ),
			persister.getEntityMode(),
			session.getFactory()
	);

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	Object result = persistenceContext.getEntity( euk );
	if ( result == null ) {
		result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session );
	}
	return result == null ? null : persistenceContext.proxyFor( result );
}
 
Example 8
Project: lams   File: Collections.java   View Source Code Vote up 4 votes
/**
    * Initialize the role of the collection.
    *
    * @param collection The collection to be updated by reachability.
    * @param type The type of the collection.
    * @param entity The owner of the collection.
 * @param session The session from which this request originates
    */
public static void processReachableCollection(
		PersistentCollection collection,
		CollectionType type,
		Object entity,
		SessionImplementor session) {
	collection.setOwner( entity );
	final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( collection );

	if ( ce == null ) {
		// refer to comment in StatefulPersistenceContext.addCollection()
		throw new HibernateException(
				"Found two representations of same collection: " +
				type.getRole()
		);
	}

	// The CollectionEntry.isReached() stuff is just to detect any silly users
	// who set up circular or shared references between/to collections.
	if ( ce.isReached() ) {
		// We've been here before
		throw new HibernateException(
				"Found shared references to a collection: " + type.getRole()
		);
	}
	ce.setReached( true );

	final SessionFactoryImplementor factory = session.getFactory();
	final CollectionPersister persister = factory.getCollectionPersister( type.getRole() );
	ce.setCurrentPersister( persister );
	//TODO: better to pass the id in as an argument?
	ce.setCurrentKey( type.getKeyOfOwner( entity, session ) );

	if ( LOG.isDebugEnabled() ) {
		if ( collection.wasInitialized() ) {
			LOG.debugf(
					"Collection found: %s, was: %s (initialized)",
					MessageHelper.collectionInfoString( persister, collection, ce.getCurrentKey(), session ),
					MessageHelper.collectionInfoString( ce.getLoadedPersister(), collection, ce.getLoadedKey(), session )
			);
		}
		else {
			LOG.debugf(
					"Collection found: %s, was: %s (uninitialized)",
					MessageHelper.collectionInfoString( persister, collection, ce.getCurrentKey(), session ),
					MessageHelper.collectionInfoString( ce.getLoadedPersister(), collection, ce.getLoadedKey(), session )
			);
		}
	}

	prepareCollectionForUpdate( collection, ce, factory );
}
 
Example 9
Project: lams   File: UpdateLockingStrategy.java   View Source Code Vote up 4 votes
@Override
public void lock(
		Serializable id,
		Object version,
		Object object,
		int timeout,
		SessionImplementor session) throws StaleObjectStateException, JDBCException {
	if ( !lockable.isVersioned() ) {
		throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
	}

	// todo : should we additionally check the current isolation mode explicitly?
	final SessionFactoryImplementor factory = session.getFactory();
	try {
		final PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql );
		try {
			lockable.getVersionType().nullSafeSet( st, version, 1, session );
			int offset = 2;

			lockable.getIdentifierType().nullSafeSet( st, id, offset, session );
			offset += lockable.getIdentifierType().getColumnSpan( factory );

			if ( lockable.isVersioned() ) {
				lockable.getVersionType().nullSafeSet( st, version, offset, session );
			}

			final int affected = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( st );
			if ( affected < 0 ) {
				if (factory.getStatistics().isStatisticsEnabled()) {
					factory.getStatisticsImplementor().optimisticFailure( lockable.getEntityName() );
				}
				throw new StaleObjectStateException( lockable.getEntityName(), id );
			}

		}
		finally {
			session.getTransactionCoordinator().getJdbcCoordinator().release( st );
		}

	}
	catch ( SQLException sqle ) {
		throw session.getFactory().getSQLExceptionHelper().convert(
				sqle,
				"could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
				sql
		);
	}
}
 
Example 10
Project: lams   File: SelectLockingStrategy.java   View Source Code Vote up 4 votes
@Override
public void lock(
		Serializable id,
		Object version,
		Object object,
		int timeout,
		SessionImplementor session) throws StaleObjectStateException, JDBCException {
	final String sql = determineSql( timeout );
	final SessionFactoryImplementor factory = session.getFactory();
	try {
		final PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql );
		try {
			getLockable().getIdentifierType().nullSafeSet( st, id, 1, session );
			if ( getLockable().isVersioned() ) {
				getLockable().getVersionType().nullSafeSet(
						st,
						version,
						getLockable().getIdentifierType().getColumnSpan( factory ) + 1,
						session
				);
			}

			final ResultSet rs = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( st );
			try {
				if ( !rs.next() ) {
					if ( factory.getStatistics().isStatisticsEnabled() ) {
						factory.getStatisticsImplementor()
								.optimisticFailure( getLockable().getEntityName() );
					}
					throw new StaleObjectStateException( getLockable().getEntityName(), id );
				}
			}
			finally {
				session.getTransactionCoordinator().getJdbcCoordinator().release( rs, st );
			}
		}
		finally {
			session.getTransactionCoordinator().getJdbcCoordinator().release( st );
		}

	}
	catch ( SQLException sqle ) {
		throw session.getFactory().getSQLExceptionHelper().convert(
				sqle,
				"could not lock: " + MessageHelper.infoString( getLockable(), id, session.getFactory() ),
				sql
			);
	}
}
 
Example 11
Project: lams   File: DefaultInitializeCollectionEventListener.java   View Source Code Vote up 4 votes
/**
 * Try to initialize a collection from the cache
 *
 * @param id The id of the collection of initialize
 * @param persister The collection persister
 * @param collection The collection to initialize
 * @param source The originating session
 *
 * @return true if we were able to initialize the collection from the cache;
 *         false otherwise.
 */
private boolean initializeCollectionFromCache(
		Serializable id,
		CollectionPersister persister,
		PersistentCollection collection,
		SessionImplementor source) {

	if ( !source.getLoadQueryInfluencers().getEnabledFilters().isEmpty()
			&& persister.isAffectedByEnabledFilters( source ) ) {
		LOG.trace( "Disregarding cached version (if any) of collection due to enabled filters" );
		return false;
	}

	final boolean useCache = persister.hasCache() && source.getCacheMode().isGetEnabled();

	if ( !useCache ) {
		return false;
	}

	final SessionFactoryImplementor factory = source.getFactory();
	final CacheKey ck = source.generateCacheKey( id, persister.getKeyType(), persister.getRole() );
	final Object ce = CacheHelper.fromSharedCache( source, ck, persister.getCacheAccessStrategy() );

	if ( factory.getStatistics().isStatisticsEnabled() ) {
		if ( ce == null ) {
			factory.getStatisticsImplementor()
					.secondLevelCacheMiss( persister.getCacheAccessStrategy().getRegion().getName() );
		}
		else {
			factory.getStatisticsImplementor()
					.secondLevelCacheHit( persister.getCacheAccessStrategy().getRegion().getName() );
		}
	}

	if ( ce == null ) {
		return false;
	}

	CollectionCacheEntry cacheEntry = (CollectionCacheEntry) persister.getCacheEntryStructure().destructure(
			ce,
			factory
	);

	final PersistenceContext persistenceContext = source.getPersistenceContext();
	cacheEntry.assemble( collection, persister, persistenceContext.getCollectionOwner( id, persister ) );
	persistenceContext.getCollectionEntry( collection ).postInitialize( collection );
	// addInitializedCollection(collection, persister, id);
	return true;
}
 
Example 12
Project: lams   File: DefaultLoadEventListener.java   View Source Code Vote up 4 votes
/**
 * Attempts to load the entity from the second-level cache.
 *
 * @param event The load event
 * @param persister The persister for the entity being requested for load
 * @param options The load options.
 *
 * @return The entity from the second-level cache, or null.
 */
protected Object loadFromSecondLevelCache(
		final LoadEvent event,
		final EntityPersister persister,
		final LoadEventListener.LoadType options) {

	final SessionImplementor source = event.getSession();
	final boolean useCache = persister.hasCache()
			&& source.getCacheMode().isGetEnabled()
			&& event.getLockMode().lessThan( LockMode.READ );

	if ( !useCache ) {
		// we can't use cache here
		return null;
	}

	final SessionFactoryImplementor factory = source.getFactory();
	final CacheKey ck = source.generateCacheKey(
			event.getEntityId(),
			persister.getIdentifierType(),
			persister.getRootEntityName()
	);

	final Object ce = CacheHelper.fromSharedCache( source, ck, persister.getCacheAccessStrategy() );
	if ( factory.getStatistics().isStatisticsEnabled() ) {
		if ( ce == null ) {
			factory.getStatisticsImplementor().secondLevelCacheMiss(
					persister.getCacheAccessStrategy().getRegion().getName()
			);
		}
		else {
			factory.getStatisticsImplementor().secondLevelCacheHit(
					persister.getCacheAccessStrategy().getRegion().getName()
			);
		}
	}

	if ( ce == null ) {
		// nothing was found in cache
		return null;
	}

	CacheEntry entry = (CacheEntry) persister.getCacheEntryStructure().destructure( ce, factory );
	Object entity = convertCacheEntryToEntity( entry, event.getEntityId(), persister, event );
	
	if ( !persister.isInstance( entity ) ) {
		throw new WrongClassException(
				"loaded object was of wrong class " + entity.getClass(),
				event.getEntityId(),
				persister.getEntityName()
			);
	}
	
	return entity;
}