org.hibernate.persister.entity.Loadable Java Examples

The following examples show how to use org.hibernate.persister.entity.Loadable. 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: DefaultEntityAliases.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String[][] getSuffixedPropertyAliases(Loadable persister) {
	final int size = persister.getPropertyNames().length;
	final String[][] suffixedPropertyAliases;
	if (size > 0) {
		suffixedPropertyAliases = new String[size][];
		for ( int j = 0; j < size; j++ ) {
			suffixedPropertyAliases[j] = getUserProvidedAliases(
					persister.getPropertyNames()[j],
					getPropertyAliases( persister, j )
			);
			suffixedPropertyAliases[j] = StringHelper.unquote( suffixedPropertyAliases[j], persister.getFactory().getDialect() );
			intern( suffixedPropertyAliases[j] );
		}
	}
	else {
		suffixedPropertyAliases = EMPTY_ARRAY_OF_ARRAY_OF_STRINGS;
	}
	return suffixedPropertyAliases;
}
 
Example #2
Source File: AbstractEmptinessExpression.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public final String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
	final String entityName = criteriaQuery.getEntityName( criteria, propertyName );
	final String actualPropertyName = criteriaQuery.getPropertyName( propertyName );
	final String sqlAlias = criteriaQuery.getSQLAlias( criteria, propertyName );

	final SessionFactoryImplementor factory = criteriaQuery.getFactory();
	final QueryableCollection collectionPersister = getQueryableCollection( entityName, actualPropertyName, factory );

	final String[] collectionKeys = collectionPersister.getKeyColumnNames();
	final String[] ownerKeys = ( (Loadable) factory.getEntityPersister( entityName ) ).getIdentifierColumnNames();

	final String innerSelect = "(select 1 from " + collectionPersister.getTableName() + " where "
			+ new ConditionFragment().setTableAlias( sqlAlias ).setCondition( ownerKeys, collectionKeys ).toFragmentString()
			+ ")";

	return excludeEmpty()
			? "exists " + innerSelect
			: "not exists " + innerSelect;
}
 
Example #3
Source File: SizeExpression.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
	final String entityName =criteriaQuery.getEntityName( criteria, propertyName );
	final String role = entityName + '.' + criteriaQuery.getPropertyName( propertyName );
	final QueryableCollection cp = (QueryableCollection) criteriaQuery.getFactory().getCollectionPersister( role );

	final String[] fk = cp.getKeyColumnNames();
	final String[] pk = ( (Loadable) cp.getOwnerEntityPersister() ).getIdentifierColumnNames();

	final ConditionFragment subQueryRestriction = new ConditionFragment()
			.setTableAlias( criteriaQuery.getSQLAlias( criteria, propertyName ) )
			.setCondition( pk, fk );

	return String.format(
			Locale.ROOT,
			"? %s (select count(*) from %s where %s)",
			op,
			cp.getTableName(),
			subQueryRestriction.toFragmentString()
	);
}
 
Example #4
Source File: SubselectFetch.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a SubselectFetch instance using the provided subselect fetch query fragment,
 * {@code subselectFetchQueryFragment}. It is assumed that {@code subselectFetchQueryFragment}
 * is the result of calling {@link #createSubselectFetchQueryFragment} with the same value
 * provided for {@code queryParameters}.
 *
 * @param subselectFetchQueryFragment - the subselect fetch query fragment;
 * @param alias - the table alias used in {@code subselectFetchQueryFragment} that
 * corresponds to {@code loadable};
 * @param loadable - the {@link Loadable} for the associated entities to be subselect fetched;
 * @param queryParameters - the query parameters;
 * @param resultingEntityKeys - the {@link EntityKey} objects for the entities to be subselect fetched;
 * @param namedParameterLocMap - mapping from named parameter to the parameter index located in the
 * subselect fetch query fragment.
 */
public SubselectFetch(
		final String subselectFetchQueryFragment,
		final String alias,
		final Loadable loadable,
		final QueryParameters queryParameters,
		final Set resultingEntityKeys,
		final Map namedParameterLocMap) {
	this.resultingEntityKeys = resultingEntityKeys;
	this.queryParameters = queryParameters;
	this.namedParameterLocMap = namedParameterLocMap;
	this.loadable = loadable;
	this.alias = alias;

	this.queryString = subselectFetchQueryFragment;
}
 
Example #5
Source File: ManyToOneType.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object resolve(Object value, SharedSessionContractImplementor session, Object owner, Boolean overridingEager) throws HibernateException {
	Object resolvedValue = super.resolve(value, session, owner, overridingEager);
	if ( isLogicalOneToOne && value != null && getPropertyName() != null ) {
		EntityEntry entry = session.getPersistenceContext().getEntry( owner );
		if ( entry != null ) {
			final Loadable ownerPersister = (Loadable) session.getFactory().getMetamodel().entityPersister( entry.getEntityName() );
			EntityUniqueKey entityKey = new EntityUniqueKey(
					ownerPersister.getEntityName(),
					getPropertyName(),
					value,
					this,
					ownerPersister.getEntityMode(),
					session.getFactory()
			);
			session.getPersistenceContext().addEntity( entityKey, owner );
		}
	}
	return resolvedValue;
}
 
Example #6
Source File: AbstractEmptinessExpression.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public final String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
	String entityName = criteriaQuery.getEntityName( criteria, propertyName );
	String actualPropertyName = criteriaQuery.getPropertyName( propertyName );
	String sqlAlias = criteriaQuery.getSQLAlias( criteria, propertyName );

	SessionFactoryImplementor factory = criteriaQuery.getFactory();
	QueryableCollection collectionPersister = getQueryableCollection( entityName, actualPropertyName, factory );

	String[] collectionKeys = collectionPersister.getKeyColumnNames();
	String[] ownerKeys = ( ( Loadable ) factory.getEntityPersister( entityName ) ).getIdentifierColumnNames();

	String innerSelect = "(select 1 from " + collectionPersister.getTableName()
	        + " where "
	        + new ConditionFragment().setTableAlias( sqlAlias ).setCondition( ownerKeys, collectionKeys ).toFragmentString()
	        + ")";

	return excludeEmpty()
	        ? "exists " + innerSelect
	        : "not exists " + innerSelect;
}
 
Example #7
Source File: SubselectFetch.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public SubselectFetch(
	//final String queryString, 
	final String alias, 
	final Loadable loadable,
	final QueryParameters queryParameters, 
	final Set resultingEntityKeys,
	final Map namedParameterLocMap
) {
	this.resultingEntityKeys = resultingEntityKeys;
	this.queryParameters = queryParameters;
	this.namedParameterLocMap = namedParameterLocMap;
	this.loadable = loadable;
	this.alias = alias;
	
	//TODO: ugly here:
	final String queryString = queryParameters.getFilteredSQL();
	int fromIndex = queryString.indexOf(" from ");
	int orderByIndex = queryString.lastIndexOf("order by");
	this.queryString = orderByIndex>0 ? 
			queryString.substring(fromIndex, orderByIndex) : 
			queryString.substring(fromIndex);
		
}
 
Example #8
Source File: SizeExpression.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
	String role = criteriaQuery.getEntityName(criteria, propertyName) + 
			'.' +  
			criteriaQuery.getPropertyName(propertyName);
	QueryableCollection cp = (QueryableCollection) criteriaQuery.getFactory()
			.getCollectionPersister(role);
	//String[] fk = StringHelper.qualify( "collection_", cp.getKeyColumnNames() );
	String[] fk = cp.getKeyColumnNames();
	String[] pk = ( (Loadable) cp.getOwnerEntityPersister() ).getIdentifierColumnNames(); //TODO: handle property-ref
	return "? " + 
			op + 
			" (select count(*) from " +
			cp.getTableName() +
			//" collection_ where " +
			" where " +
			new ConditionFragment()
					.setTableAlias( criteriaQuery.getSQLAlias(criteria, propertyName) )
					.setCondition(pk, fk)
					.toFragmentString() +
			")";
}
 
Example #9
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected boolean hasSubselectLoadableCollections() {
	final Loadable[] loadables = getEntityPersisters();
	for ( Loadable loadable : loadables ) {
		if ( loadable.hasSubselectLoadableCollections() ) {
			return true;
		}
	}
	return false;
}
 
Example #10
Source File: AbstractEntityJoinWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected final void initProjection(
		final String projectionString,
		final String whereString,
		final String orderByString,
		final String groupByString,
		final LockOptions lockOptions) throws MappingException {
	walkEntityTree( persister, getAlias() );
	persisters = new Loadable[0];
	initStatementString(projectionString, whereString, orderByString, groupByString, lockOptions);
}
 
Example #11
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected boolean shouldUseFollowOnLocking(
		QueryParameters parameters,
		Dialect dialect,
		List<AfterLoadAction> afterLoadActions) {
	if ( ( parameters.getLockOptions().getFollowOnLocking() == null && dialect.useFollowOnLocking( parameters ) ) ||
			( parameters.getLockOptions().getFollowOnLocking() != null && parameters.getLockOptions().getFollowOnLocking() ) ) {
		// currently only one lock mode is allowed in follow-on locking
		final LockMode lockMode = determineFollowOnLockMode( parameters.getLockOptions() );
		final LockOptions lockOptions = new LockOptions( lockMode );
		if ( lockOptions.getLockMode() != LockMode.UPGRADE_SKIPLOCKED ) {
			if ( lockOptions.getLockMode() != LockMode.NONE ) {
				LOG.usingFollowOnLocking();
			}
			lockOptions.setTimeOut( parameters.getLockOptions().getTimeOut() );
			lockOptions.setScope( parameters.getLockOptions().getScope() );
			afterLoadActions.add(
					new AfterLoadAction() {
						@Override
						public void afterLoad(SharedSessionContractImplementor session, Object entity, Loadable persister) {
							( (Session) session ).buildLockRequest( lockOptions ).lock(
									persister.getEntityName(),
									entity
							);
						}
					}
			);
			parameters.setLockOptions( new LockOptions() );
			return true;
		}
	}
	return false;
}
 
Example #12
Source File: DefaultEntityAliases.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Calculate and cache select-clause suffixes.
 * @param map 
 */
public DefaultEntityAliases(Map userProvidedAliases, Loadable persister, String suffix) {
	this.suffix = suffix;
	this.userProvidedAliases = userProvidedAliases;
	
	String[] keyColumnsCandidates = getUserProvidedAliases(
			persister.getIdentifierPropertyName(), 
			(String[]) null
		); 
	if (keyColumnsCandidates==null) {
		suffixedKeyColumns = getUserProvidedAliases(
				"id", 
				getIdentifierAliases(persister, suffix)
			);
	} 
	else {
		suffixedKeyColumns = keyColumnsCandidates;
	}
	intern(suffixedKeyColumns);
	
	suffixedPropertyColumns = getSuffixedPropertyAliases(persister);
	suffixedDiscriminatorColumn = getUserProvidedAlias(
			"class", 
			getDiscriminatorAlias(persister, suffix)
		);
	if ( persister.isVersioned() ) { 
		suffixedVersionColumn = suffixedPropertyColumns[ persister.getVersionProperty() ];
	}
	else {
		suffixedVersionColumn = null;
	}
	rowIdAlias = Loadable.ROWID_ALIAS + suffix; // TODO: not visible to the user!
}
 
Example #13
Source File: Loader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected boolean hasSubselectLoadableCollections() {
	final Loadable[] loadables = getEntityPersisters();
	for (int i=0; i<loadables.length; i++ ) {
		if ( loadables[i].hasSubselectLoadableCollections() ) return true;
	}
	return false;
}
 
Example #14
Source File: Loader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void createSubselects(List keys, QueryParameters queryParameters, SessionImplementor session) {
	if ( keys.size() > 1 ) { //if we only returned one entity, query by key is more efficient
		
		Set[] keySets = transpose(keys);
		
		Map namedParameterLocMap = buildNamedParameterLocMap( queryParameters );
		
		final Loadable[] loadables = getEntityPersisters();
		final String[] aliases = getAliases();
		final Iterator iter = keys.iterator();
		while ( iter.hasNext() ) {
			
			final EntityKey[] rowKeys = (EntityKey[]) iter.next();
			for ( int i=0; i<rowKeys.length; i++ ) {
				
				if ( rowKeys[i]!=null && loadables[i].hasSubselectLoadableCollections() ) {
					
					SubselectFetch subselectFetch = new SubselectFetch( 
							//getSQLString(), 
							aliases[i], 
							loadables[i], 
							queryParameters, 
							keySets[i],
							namedParameterLocMap
						);
					
					session.getPersistenceContext()
							.getBatchFetchQueue()
							.addSubselect( rowKeys[i], subselectFetch );
				}
				
			}
			
		}
	}
}
 
Example #15
Source File: CriteriaQueryTranslator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public TypedValue getTypedIdentifierValue(Criteria subcriteria, Object value) {
	final Loadable loadable = ( Loadable ) getPropertyMapping( getEntityName( subcriteria ) );
	return new TypedValue(
			loadable.getIdentifierType(),
	        value,
	        EntityMode.POJO
	);
}
 
Example #16
Source File: Loader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Check the version of the object in the <tt>ResultSet</tt> against
 * the object version in the session cache, throwing an exception
 * if the version numbers are different
 */
private void checkVersion(
        final int i,
        final Loadable persister,
        final Serializable id,
        final Object entity,
        final ResultSet rs,
        final SessionImplementor session) 
throws HibernateException, SQLException {

	Object version = session.getPersistenceContext().getEntry( entity ).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();
		Object currentVersion = versionType.nullSafeGet(
				rs,
				getEntityAliases()[i].getSuffixedVersionAliases(),
				session,
				null
			);
		if ( !versionType.isEqual(version, currentVersion) ) {
			if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
				session.getFactory().getStatisticsImplementor()
						.optimisticFailure( persister.getEntityName() );
			}
			throw new StaleObjectStateException( persister.getEntityName(), id );
		}
	}

}
 
Example #17
Source File: BasicLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void postInstantiate() {
	Loadable[] persisters = getEntityPersisters();
	String[] suffixes = getSuffixes();
	descriptors = new EntityAliases[persisters.length];
	for ( int i=0; i<descriptors.length; i++ ) {
		descriptors[i] = new DefaultEntityAliases( persisters[i], suffixes[i] );
	}

	CollectionPersister[] collectionPersisters = getCollectionPersisters();
	int bagCount = 0;
	if ( collectionPersisters != null ) {
		String[] collectionSuffixes = getCollectionSuffixes();
		collectionDescriptors = new CollectionAliases[collectionPersisters.length];
		for ( int i = 0; i < collectionPersisters.length; i++ ) {
			if ( isBag( collectionPersisters[i] ) ) {
				bagCount++;
			}
			collectionDescriptors[i] = new GeneratedCollectionAliases(
					collectionPersisters[i],
					collectionSuffixes[i]
				);
		}
	}
	else {
		collectionDescriptors = null;
	}
	if ( bagCount > 1 ) {
		throw new HibernateException( "cannot simultaneously fetch multiple bags" );
	}
}
 
Example #18
Source File: DefaultEntityAliases.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String[][] getSuffixedPropertyAliases(Loadable persister) {
	int size = persister.getPropertyNames().length;
	String[][] suffixedPropertyAliases = new String[size][];
	for ( int j = 0; j < size; j++ ) {
		suffixedPropertyAliases[j] = getUserProvidedAliases(
				persister.getPropertyNames()[j],
				getPropertyAliases(persister, j)
			);
		intern( suffixedPropertyAliases[j] );
	}			
	return suffixedPropertyAliases;
}
 
Example #19
Source File: Loader.java    From cacheonix-core with GNU Lesser General Public License v2.1 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 lockMode,
        final SessionImplementor session) 
throws HibernateException, SQLException {

	if ( !persister.isInstance( object, session.getEntityMode() ) ) {
		throw new WrongClassException( 
				"loaded object was of wrong class " + object.getClass(), 
				key.getIdentifier(), 
				persister.getEntityName() 
			);
	}

	if ( LockMode.NONE != lockMode && upgradeLocks() ) { //no point doing this if NONE was requested

		final boolean isVersionCheckNeeded = persister.isVersioned() &&
				session.getPersistenceContext().getEntry(object)
						.getLockMode().lessThan( lockMode );
		// we don't need to worry about existing version being uninitialized
		// because this block isn't called by a re-entrant load (re-entrant
		// loads _always_ have lock mode NONE)
		if (isVersionCheckNeeded) {
			//we only check the version when _upgrading_ lock modes
			checkVersion( i, persister, key.getIdentifier(), object, rs, session );
			//we need to upgrade the lock mode to the mode requested
			session.getPersistenceContext().getEntry(object)
					.setLockMode(lockMode);
		}
	}
}
 
Example #20
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void createSubselects(List keys, QueryParameters queryParameters, SharedSessionContractImplementor session) {
	if ( keys.size() > 1 ) { //if we only returned one entity, query by key is more efficient

		Set[] keySets = transpose( keys );

		Map namedParameterLocMap = buildNamedParameterLocMap( queryParameters );

		final Loadable[] loadables = getEntityPersisters();
		final String[] aliases = getAliases();
		final String subselectQueryString = SubselectFetch.createSubselectFetchQueryFragment( queryParameters );
		for ( Object key : keys ) {
			final EntityKey[] rowKeys = (EntityKey[]) key;
			for ( int i = 0; i < rowKeys.length; i++ ) {

				if ( rowKeys[i] != null && loadables[i].hasSubselectLoadableCollections() ) {

					SubselectFetch subselectFetch = new SubselectFetch(
							subselectQueryString,
							aliases[i],
							loadables[i],
							queryParameters,
							keySets[i],
							namedParameterLocMap
					);

					session.getPersistenceContext()
							.getBatchFetchQueue()
							.addSubselect( rowKeys[i], subselectFetch );
				}

			}

		}
	}
}
 
Example #21
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check the version of the object in the <tt>ResultSet</tt> against
 * the object version in the session cache, throwing an exception
 * if the version numbers are different
 */
private void checkVersion(
		final int i,
		final Loadable persister,
		final Serializable id,
		final Object entity,
		final ResultSet rs,
		final SharedSessionContractImplementor session) throws HibernateException, SQLException {

	Object version = session.getPersistenceContext().getEntry( entity ).getVersion();

	if ( version != null ) { //null version means the object is in the process of being loaded somewhere else in the ResultSet
		final VersionType versionType = persister.getVersionType();
		final Object currentVersion = versionType.nullSafeGet(
				rs,
				getEntityAliases()[i].getSuffixedVersionAliases(),
				session,
				null
		);
		if ( !versionType.isEqual( version, currentVersion ) ) {
			if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
				session.getFactory().getStatistics().optimisticFailure( persister.getEntityName() );
			}
			throw new StaleObjectStateException( persister.getEntityName(), id );
		}
	}

}
 
Example #22
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 #23
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determine the concrete class of an instance in the <tt>ResultSet</tt>
 */
private String getInstanceClass(
		final ResultSet rs,
		final int i,
		final Loadable persister,
		final Serializable id,
		final SharedSessionContractImplementor session) throws HibernateException, SQLException {

	if ( persister.hasSubclasses() ) {

		// Code to handle subclasses of topClass
		final Object discriminatorValue = persister.getDiscriminatorType().nullSafeGet(
				rs,
				getEntityAliases()[i].getSuffixedDiscriminatorAlias(),
				session,
				null
		);

		final String result = persister.getSubclassForDiscriminatorValue( discriminatorValue );

		if ( result == null ) {
			//woops we got an instance of another class hierarchy branch
			throw new WrongClassException(
					"Discriminator: " + discriminatorValue,
					id,
					persister.getEntityName()
			);
		}

		return result;

	}
	else {
		return persister.getEntityName();
	}
}
 
Example #24
Source File: Loader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine the concrete class of an instance in the <tt>ResultSet</tt>
 */
private String getInstanceClass(
        final ResultSet rs,
        final int i,
        final Loadable persister,
        final Serializable id,
        final SessionImplementor session) 
throws HibernateException, SQLException {

	if ( persister.hasSubclasses() ) {

		// Code to handle subclasses of topClass
		Object discriminatorValue = persister.getDiscriminatorType().nullSafeGet(
				rs,
				getEntityAliases()[i].getSuffixedDiscriminatorAlias(),
				session,
				null
			);

		final String result = persister.getSubclassForDiscriminatorValue( discriminatorValue );

		if ( result == null ) {
			//woops we got an instance of another class hierarchy branch
			throw new WrongClassException( 
					"Discriminator: " + discriminatorValue,
					id,
					persister.getEntityName() 
				);
		}

		return result;

	}
	else {
		return persister.getEntityName();
	}
}
 
Example #25
Source File: ResultSetProcessingContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void createSubselects() {
	if ( subselectLoadableEntityKeyMap == null || nRowsRead <= 1 ) {
		LOG.tracef(
				"Skipping create subselects because there are fewer than 2 results, so query by key is more efficient.",
				getClass().getName()
		);
		return; // early return
	}

	final Map<String, int[]> namedParameterLocMap =
			ResultSetProcessorHelper.buildNamedParameterLocMap( queryParameters, namedParameterContext );

	final String subselectQueryString = SubselectFetch.createSubselectFetchQueryFragment( queryParameters );
	for ( Map.Entry<EntityReference, Set<EntityKey>> entry : subselectLoadableEntityKeyMap.entrySet() ) {
		if ( ! entry.getKey().getEntityPersister().hasSubselectLoadableCollections() ) {
			continue;
		}

		SubselectFetch subselectFetch = new SubselectFetch(
				subselectQueryString,
				aliasResolutionContext.resolveSqlTableAliasFromQuerySpaceUid( entry.getKey().getQuerySpaceUid() ),
				(Loadable) entry.getKey().getEntityPersister(),
				queryParameters,
				entry.getValue(),
				namedParameterLocMap
		);

		for ( EntityKey key : entry.getValue() ) {
			session.getPersistenceContext().getBatchFetchQueue().addSubselect( key, subselectFetch );
		}
	}
}
 
Example #26
Source File: AbstractRowReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void postLoad(
		PostLoadEvent postLoadEvent,
		ResultSetProcessingContextImpl context,
		List<HydratedEntityRegistration> hydratedEntityRegistrations,
		List<AfterLoadAction> afterLoadActionList) {
	// Until this entire method is refactored w/ polymorphism, postLoad was
	// split off from initializeEntity.  It *must* occur after
	// endCollectionLoad to ensure the collection is in the
	// persistence context.
	if ( hydratedEntityRegistrations == null ) {
		return;
	}

	for ( HydratedEntityRegistration registration : hydratedEntityRegistrations ) {
		TwoPhaseLoad.postLoad( registration.getInstance(), context.getSession(), postLoadEvent );
		if ( afterLoadActionList != null ) {
			for ( AfterLoadAction afterLoadAction : afterLoadActionList ) {
				afterLoadAction.afterLoad(
						context.getSession(),
						registration.getInstance(),
						(Loadable) registration.getEntityReference().getEntityPersister()
				);
			}
		}
	}

}
 
Example #27
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 #28
Source File: DefaultEntityAliases.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Calculate and cache select-clause aliases
 *
 * @param userProvidedAliases The explicit aliases provided in a result-set mapping.
 * @param persister The persister for which we are generating select aliases
 * @param suffix The calculated suffix.
 */
public DefaultEntityAliases(
		Map userProvidedAliases,
		Loadable persister,
		String suffix) {
	this.suffix = suffix.intern();
	this.userProvidedAliases = userProvidedAliases;

	suffixedKeyColumns = determineKeyAlias( persister, suffix );
	suffixedPropertyColumns = determinePropertyAliases( persister );
	suffixedDiscriminatorColumn = determineDiscriminatorAlias( persister, suffix );
	suffixedVersionColumn = determineVersionAlias( persister );
	rowIdAlias = (Loadable.ROWID_ALIAS + suffix).intern(); // TODO: not visible to the user!
}
 
Example #29
Source File: ReactiveAbstractEntityLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected CompletionStage<List<Object>> loadReactiveEntity(
		final SessionImplementor session,
		final Object id,
		final Type identifierType,
		final Object optionalObject,
		final String optionalEntityName,
		final Serializable optionalIdentifier,
		LockOptions lockOptions) throws HibernateException {

	QueryParameters parameters = buildQueryParameters(
			id, identifierType,
			optionalObject,
			optionalEntityName,
			optionalIdentifier,
			lockOptions
	);

	return doReactiveQueryAndInitializeNonLazyCollections( session, parameters, false )
		.handle( (list, err) -> {
			LOG.debug( "Done entity load" );
			Loadable[] persisters = getEntityPersisters();
			CompletionStages.logSqlException( err,
					() -> "could not load an entity: " +
							infoString(
									persisters[persisters.length - 1],
									id,
									identifierType,
									getFactory()
							),
					getSQLString()
			);
			return CompletionStages.returnOrRethrow( err, list );
		} );
}
 
Example #30
Source File: AbstractCollectionPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String resolveTableAlias(String columnReference) {
	if ( elementPersister == null ) {
		// we have collection of non-entity elements...
		return rootAlias;
	}
	else {
		return ( (Loadable) elementPersister ).getTableAliasForColumn( columnReference, rootAlias );
	}
}