org.hibernate.sql.JoinType Java Examples

The following examples show how to use org.hibernate.sql.JoinType. 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: OuterJoinableAssociation.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public OuterJoinableAssociation(
		PropertyPath propertyPath,
		AssociationType joinableType,
		String lhsAlias,
		String[] lhsColumns,
		String rhsAlias,
		JoinType joinType,
		String withClause,
		boolean hasRestriction,
		SessionFactoryImplementor factory,
		Map enabledFilters) throws MappingException {
	this.propertyPath = propertyPath;
	this.joinableType = joinableType;
	this.lhsAlias = lhsAlias;
	this.lhsColumns = lhsColumns;
	this.rhsAlias = rhsAlias;
	this.joinType = joinType;
	this.joinable = joinableType.getAssociatedJoinable( factory );
	this.rhsColumns = JoinHelper.getRHSColumnNames( joinableType, factory );
	this.on = joinableType.getOnCondition( rhsAlias, factory, enabledFilters )
			+ ( withClause == null || withClause.trim().length() == 0 ? "" : " and ( " + withClause + " )" );
	this.hasRestriction = hasRestriction;
	this.enabledFilters = enabledFilters; // needed later for many-to-many/filter application
}
 
Example #2
Source File: OuterJoinableAssociation.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static OuterJoinableAssociation createRoot(
		AssociationType joinableType,
		String alias,
		SessionFactoryImplementor factory) {
	return new OuterJoinableAssociation(
			new PropertyPath(),
			joinableType,
			null,
			null,
			alias,
			JoinType.LEFT_OUTER_JOIN,
			null,
			false,
			factory,
			Collections.EMPTY_MAP
	);
}
 
Example #3
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine the appropriate type of join (if any) to use to fetch the
 * given association.
 *
 * @param persister The owner of the association.
 * @param path The path to the association
 * @param propertyNumber The property number representing the association.
 * @param associationType The association type.
 * @param metadataFetchMode The metadata-defined fetch mode.
 * @param metadataCascadeStyle The metadata-defined cascade style.
 * @param lhsTable The owner table
 * @param lhsColumns The owner join columns
 * @param nullable Is the association nullable.
 * @param currentDepth Current join depth
 *
 * @return type of join to use ({@link org.hibernate.sql.JoinType#INNER_JOIN},
 * {@link org.hibernate.sql.JoinType#LEFT_OUTER_JOIN}, or -1 to indicate no joining.
 *
 * @throws MappingException ??
 */
protected JoinType getJoinType(
		OuterJoinLoadable persister,
		final PropertyPath path,
		int propertyNumber,
		AssociationType associationType,
		FetchMode metadataFetchMode,
		CascadeStyle metadataCascadeStyle,
		String lhsTable,
		String[] lhsColumns,
		final boolean nullable,
		final int currentDepth) throws MappingException {
	return getJoinType(
			associationType,
			metadataFetchMode,
			path,
			lhsTable,
			lhsColumns,
			nullable,
			currentDepth,
			metadataCascadeStyle
	);
}
 
Example #4
Source File: CriteriaQueryTranslator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void createAssociationPathCriteriaMap() {
	final Iterator<CriteriaImpl.Subcriteria> iter = rootCriteria.iterateSubcriteria();
	while ( iter.hasNext() ) {
		CriteriaImpl.Subcriteria crit = iter.next();
		String wholeAssociationPath = getWholeAssociationPath( crit );
		Object old = associationPathCriteriaMap.put( wholeAssociationPath, crit );
		if ( old != null ) {
			throw new QueryException( "duplicate association path: " + wholeAssociationPath );
		}
		JoinType joinType = crit.getJoinType();
		old = associationPathJoinTypesMap.put( wholeAssociationPath, joinType );
		if ( old != null ) {
			// TODO : not so sure this is needed...
			throw new QueryException( "duplicate association path: " + wholeAssociationPath );
		}
		if ( crit.getWithClause() != null ) {
			this.withClauseMap.put( wholeAssociationPath, crit.getWithClause() );
		}
	}
}
 
Example #5
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add on association (one-to-one, many-to-one, or a collection) to a list
 * of associations to be fetched by outerjoin (if necessary)
 */
private void addAssociationToJoinTreeIfNecessary(
		final AssociationType type,
		final String[] aliasedLhsColumns,
		final String alias,
		final PropertyPath path,
		int currentDepth,
		final JoinType joinType) throws MappingException {
	if ( joinType != JoinType.NONE ) {
		addAssociationToJoinTree(
				type,
				aliasedLhsColumns,
				alias,
				path,
				currentDepth,
				joinType
		);
	}
}
 
Example #6
Source File: JoinProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Translates an AST join type (i.e., the token type) into a JoinFragment.XXX join type.
 *
 * @param astJoinType The AST join type (from HqlSqlTokenTypes or SqlTokenTypes)
 *
 * @return a JoinFragment.XXX join type.
 *
 * @see JoinFragment
 * @see SqlTokenTypes
 */
public static JoinType toHibernateJoinType(int astJoinType) {
	switch ( astJoinType ) {
		case LEFT_OUTER: {
			return JoinType.LEFT_OUTER_JOIN;
		}
		case INNER: {
			return JoinType.INNER_JOIN;
		}
		case RIGHT_OUTER: {
			return JoinType.RIGHT_OUTER_JOIN;
		}
		case FULL: {
			return JoinType.FULL_JOIN;
		}
		default: {
			throw new AssertionFailure( "undefined join type " + astJoinType );
		}
	}
}
 
Example #7
Source File: CriteriaJoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected JoinType getJoinType(
		AssociationType associationType,
		FetchMode config,
		PropertyPath path,
		String lhsTable,
		String[] lhsColumns,
		boolean nullable,
		int currentDepth,
		CascadeStyle cascadeStyle) throws MappingException {
	return getJoinType(
			null,
			path,
			-1,
			associationType,
			config,
			cascadeStyle,
			lhsTable,
			lhsColumns,
			nullable,
			currentDepth
	);
}
 
Example #8
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine the appropriate associationType of join (if any) to use to fetch the
 * given association.
 *
 * @param associationType The association associationType.
 * @param config The metadata-defined fetch mode.
 * @param path The path to the association
 * @param lhsTable The owner table
 * @param lhsColumns The owner join columns
 * @param nullable Is the association nullable.
 * @param currentDepth Current join depth
 * @param cascadeStyle The metadata-defined cascade style.
 *
 * @return type of join to use ({@link org.hibernate.sql.JoinType#INNER_JOIN},
 * {@link org.hibernate.sql.JoinType#LEFT_OUTER_JOIN}, or -1 to indicate no joining.
 *
 * @throws MappingException ??
 */
protected JoinType getJoinType(
		AssociationType associationType,
		FetchMode config,
		PropertyPath path,
		String lhsTable,
		String[] lhsColumns,
		boolean nullable,
		int currentDepth,
		CascadeStyle cascadeStyle) throws MappingException {
	if ( !isJoinedFetchEnabled( associationType, config, cascadeStyle ) ) {
		return JoinType.NONE;
	}
	if ( isTooDeep( currentDepth ) || ( associationType.isCollectionType() && isTooManyCollections() ) ) {
		return JoinType.NONE;
	}
	if ( isDuplicateAssociation( lhsTable, lhsColumns, associationType ) ) {
		return JoinType.NONE;
	}
	return getJoinType( nullable, currentDepth );
}
 
Example #9
Source File: AbstractEntityPersister.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected JoinFragment createJoin(int[] tableNumbers, String drivingAlias) {
	final String[] keyCols = StringHelper.qualify( drivingAlias, getSubclassTableKeyColumns( tableNumbers[0] ) );
	final JoinFragment jf = getFactory().getDialect().createOuterJoinFragment();
	// IMPL NOTE : notice that we skip the first table; it is the driving table!
	for ( int i = 1; i < tableNumbers.length; i++ ) {
		final int j = tableNumbers[i];
		jf.addJoin(
				getSubclassTableName( j ),
				generateTableAlias( getRootAlias(), j ),
				keyCols,
				getSubclassTableKeyColumns( j ),
				isInverseSubclassTable( j ) || isNullableSubclassTable( j )
						? JoinType.LEFT_OUTER_JOIN
						: JoinType.INNER_JOIN
		);
	}
	return jf;
}
 
Example #10
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Should we join this association?
 */
protected boolean isJoinable(
		final JoinType joinType,
		final Set visitedAssociationKeys,
		final String lhsTable,
		final String[] lhsColumnNames,
		final AssociationType type,
		final int depth) {

	if ( joinType == JoinType.NONE ) {
		return false;
	}

	if ( joinType == JoinType.INNER_JOIN ) {
		return true;
	}

	Integer maxFetchDepth = getFactory().getSessionFactoryOptions().getMaximumFetchDepth();
	final boolean tooDeep = maxFetchDepth != null && depth >= maxFetchDepth;

	return !tooDeep && !isDuplicateAssociation( lhsTable, lhsColumnNames, type );
}
 
Example #11
Source File: EntityJoinFromElement.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addJoin(
		String tableName,
		String alias,
		String[] fkColumns,
		String[] pkColumns,
		JoinType joinType,
		String on) {
}
 
Example #12
Source File: EntityJoinFromElement.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addJoin(
		String tableName,
		String alias,
		String[] fkColumns,
		String[] pkColumns,
		JoinType joinType) {
}
 
Example #13
Source File: EntityJoinFromElement.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public EntityJoinJoinSequenceImpl(
		SessionFactoryImplementor factory,
		EntityType entityType,
		String entityTableText,
		String entityTableAlias,
		JoinType joinType) {
	super( factory );
	this.factory = factory;
	this.entityType = entityType;
	this.entityTableText = entityTableText;
	this.entityTableAlias = entityTableAlias;
	this.joinType = joinType;

	setUseThetaStyle( false );
}
 
Example #14
Source File: FromElementFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private JoinSequence createJoinSequence(String roleAlias, JoinType joinType) {
	SessionFactoryHelper sessionFactoryHelper = fromClause.getSessionFactoryHelper();
	String[] joinColumns = getColumns();
	if ( collectionType == null ) {
		throw new IllegalStateException( "collectionType is null!" );
	}
	return sessionFactoryHelper.createJoinSequence( implied, collectionType, roleAlias, joinType, joinColumns );
}
 
Example #15
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<E> getByCriteriaWithInnerJoinByOrder(Criterion criterion, String order, String[] orderBy, Integer count, String aliasTable, Criterion aliasCriterion) {
	Session session = getCurrentSession();
	List<E> fetchedList = new ArrayList<E>();
	//logger.info("Entity: " + entityClass + ", current Session = " + session);
	Criteria criteria = session.createCriteria(entityClass);
	criteria.add(criterion); 
	criteria.createAlias(aliasTable, aliasTable, org.hibernate.sql.JoinType.INNER_JOIN).add(aliasCriterion);
	if (orderBy != null) {
		for(int i = 0; i< orderBy.length; i++){
			if (order != null && order.equalsIgnoreCase("desc")) {
				criteria.addOrder(Order.desc(orderBy[i]));
			} else {
				criteria.addOrder(Order.asc(orderBy[i]));
			}
		}
	}
	if(count != null && count > 0){
		criteria.setMaxResults(count);
	}
	try {	
		fetchedList = criteria.list();
		return fetchedList;
	} catch (Exception e) {
		logger.error("getByCriteriaWithInnerJoinByOrder failed, criteria = " + criterion.toString(), e);
		throw new HibernateException("getByCriteriaWithInnerJoinByOrder failed, criteria = " + criterion.toString());
	}
}
 
Example #16
Source File: JoinSequence.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
Join(
		SessionFactoryImplementor factory,
		AssociationType associationType,
		String alias,
		JoinType joinType,
		String[][] lhsColumns) throws MappingException {
	this.associationType = associationType;
	this.joinable = associationType.getAssociatedJoinable( factory );
	this.alias = alias;
	this.joinType = joinType;
	this.lhsColumns = lhsColumns;
}
 
Example #17
Source File: JoinSequence.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean needsTableGroupJoin(List<Join> joins, String withClauseFragment) {
	// If the rewrite is disabled or we don't have a with clause, we don't need a table group join
	if ( !collectionJoinSubquery || StringHelper.isEmpty( withClauseFragment ) ) {
		return false;
	}
	// If we only have one join, a table group join is only necessary if subclass columns are used in the with clause
	if ( joins.size() < 2 ) {
		return isSubclassAliasDereferenced( joins.get( 0 ), withClauseFragment );
	}
	// If more than one table is involved and this is not an inner join, we definitely need a table group join
	// i.e. a left join has to be made for the table group to retain the join semantics
	if ( joins.get( 0 ).getJoinType() != JoinType.INNER_JOIN ) {
		return true;
	}
	// If a subclass columns is used, we need a table group, otherwise we generate wrong SQL by putting the ON condition to the first join
	if ( isSubclassAliasDereferenced( joins.get( 0 ), withClauseFragment ) ) {
		return true;
	}

	// Normally, the ON condition of a HQL join is put on the ON clause of the first SQL join
	// Since the ON condition could refer to columns from subsequently joined tables i.e. joins with index > 0
	// or could refer to columns of subclass tables, the SQL could be wrong
	// To avoid generating wrong SQL, we detect these cases here i.e. a subsequent join alias is used in the ON condition
	// If we find out that this is the case, we return true and generate a table group join

	// Skip the first since that is the driving join
	for ( int i = 1; i < joins.size(); i++ ) {
		Join join = joins.get( i );

		if ( isAliasDereferenced( withClauseFragment, join.getAlias() ) || isSubclassAliasDereferenced( join, withClauseFragment ) ) {
			return true;
		}
	}

	return false;
}
 
Example #18
Source File: EntityJoinWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected JoinType getJoinType(
		OuterJoinLoadable persister,
		PropertyPath path,
		int propertyNumber,
		AssociationType associationType,
		FetchMode metadataFetchMode,
		CascadeStyle metadataCascadeStyle,
		String lhsTable,
		String[] lhsColumns,
		boolean nullable,
		int currentDepth) throws MappingException {
	// NOTE : we override this form here specifically to account for
	// fetch profiles.
	// TODO : how to best handle criteria queries?
	if ( lockOptions.getLockMode().greaterThan( LockMode.READ ) ) {
		return JoinType.NONE;
	}
	if ( isTooDeep( currentDepth )
			|| ( associationType.isCollectionType() && isTooManyCollections() ) ) {
		return JoinType.NONE;
	}
	if ( !isJoinedFetchEnabledInMapping( metadataFetchMode, associationType )
			&& !isJoinFetchEnabledByProfile( persister, path, propertyNumber ) ) {
		return JoinType.NONE;
	}
	if ( isDuplicateAssociation( lhsTable, lhsColumns, associationType ) ) {
		return JoinType.NONE;
	}
	return getJoinType( nullable, currentDepth );
}
 
Example #19
Source File: DocumentResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Integer getDocumentCountForNominalLabelAndCrisis(Long nominalLabelID, String crisisCode) {
	if (nominalLabelID != null) {
		String aliasTable = "documentNominalLabels";
		String aliasTableKeyField = "documentNominalLabels.id.nominalLabelId";
		String[] orderBy = {"documentId"};
		Criteria criteria = null;
		
		try {
			CollectionDTO cdto = crisisEJB.getCrisisByCode(crisisCode); 
			
			Criterion criterion = Restrictions.conjunction()
					.add(Restrictions.eq("collection.id",cdto.getCrisisID()))
					.add(Restrictions.eq("hasHumanLabels", true));
			
			Criterion aliasCriterion =  Restrictions.eq(aliasTableKeyField, nominalLabelID);
			
			// get just the documentIDs
			Projection projection = Projections.property("documentId");
			
			//List<Document> docList = this.getByCriteriaWithInnerJoinByOrder(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion);
			criteria = createCriteria(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion, new Projection[] {projection}, JoinType.LEFT_OUTER_JOIN);
			List<Long> docIDList = criteria.list();
			
			if (docIDList != null && !docIDList.isEmpty()) {
				return docIDList.size();
			}
		} catch (Exception e) {
			logger.error("getDocumentCountForNominalLabelAndCrisis failed, criteria = " + criteria.toString(), e);
			return 0;
		}
	}
	return 0;
}
 
Example #20
Source File: QuestionDAO.java    From mamute with Apache License 2.0 5 votes vote down vote up
public List<Question> allVisible(Integer page) {
	Criteria criteria = session.createCriteria(Question.class, "q")
			.createCriteria("q.solution.information", JoinType.LEFT_OUTER_JOIN)
			.addOrder(desc("q.lastUpdatedAt"))
			.setFirstResult(firstResultOf(page))
			.setMaxResults(PAGE_SIZE);

	return addInvisibleFilter(criteria).list();
}
 
Example #21
Source File: DocumentResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<DocumentDTO> getDocumentForNominalLabelAndCrisis(List<Long> nominalLabelID, Long crisisId) {
	
	List<DocumentDTO> dtoList = new ArrayList<DocumentDTO>();
	
	if (nominalLabelID != null) {
		String aliasTable = "documentNominalLabels";
		String aliasTableKeyField = "documentNominalLabels.id.nominalLabelId";
		Criteria criteria = null;
		
		try {
			
			Criterion criterion = Restrictions.conjunction()
					.add(Restrictions.eq("collection.id", crisisId))
					.add(Restrictions.eq("hasHumanLabels", true));
			
			Criterion aliasCriterion =  Restrictions.in(aliasTableKeyField, nominalLabelID);
			
			// get just the documentIDs
			Projection projection = Projections.property("documentId");
			
			//List<Document> docList = this.getByCriteriaWithInnerJoinByOrder(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion);
			criteria = createCriteria(criterion, null, null, null, aliasTable, aliasCriterion, null, JoinType.INNER_JOIN);
			List<Document> docList = criteria.list();
			
			if (docList != null && !docList.isEmpty()) {
				for (Document doc : docList) {
					DocumentDTO dto = new DocumentDTO(doc);
					dtoList.add(dto);
				}
			}
		} catch (Exception e) {
			logger.error("getDocumentCountForNominalLabelAndCrisis failed, criteria = " + criteria.toString(), e);
		}
	}
	
	return dtoList;
}
 
Example #22
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
public Criteria createCriteria(Criterion criterion,
		String order, String[] orderBy, Integer count, String aliasTable,
		Criterion aliasCriterion, Projection[] projections, JoinType joinType) {
	
	Session session = getCurrentSession();
	List fetchedList = new ArrayList();
	//logger.info("Entity: " + entityClass + ", current Session = " + session);
	Criteria criteria = session.createCriteria(entityClass);
	criteria.add(criterion); 
	criteria.createAlias(aliasTable, aliasTable, joinType).add(aliasCriterion);
	if (orderBy != null) {
		for(int i = 0; i< orderBy.length; i++){
			if (order != null && order.equalsIgnoreCase("desc")) {
				criteria.addOrder(Order.desc(orderBy[i]));
			} else {
				criteria.addOrder(Order.asc(orderBy[i]));
			}
		}
	}
	if(count != null && count > 0){
		criteria.setMaxResults(count);
	}
	
	// set projections
	setProjections(criteria, projections);
	
	return criteria;
	
}
 
Example #23
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Process a particular association owned by the entity
 *
 * @param associationType The type representing the association to be
 * processed.
 * @param persister The owner of the association to be processed.
 * @param propertyNumber The property number for the association
 * (relative to the persister).
 * @param alias The entity alias
 * @param path The path to the association
 * @param nullable is the association nullable (which I think is supposed
 * to indicate inner/outer join semantics).
 * @param currentDepth The current join depth
 *
 * @throws org.hibernate.MappingException ???
 */
private void walkEntityAssociationTree(
		final AssociationType associationType,
		final OuterJoinLoadable persister,
		final int propertyNumber,
		final String alias,
		final PropertyPath path,
		final boolean nullable,
		final int currentDepth) throws MappingException {
	String[] aliasedLhsColumns = JoinHelper.getAliasedLHSColumnNames(
			associationType, alias, propertyNumber, persister, getFactory()
	);
	String[] lhsColumns = JoinHelper.getLHSColumnNames(
			associationType, propertyNumber, persister, getFactory()
	);
	String lhsTable = JoinHelper.getLHSTableName( associationType, propertyNumber, persister );

	PropertyPath subPath = path.append( persister.getSubclassPropertyName( propertyNumber ) );
	JoinType joinType = getJoinType(
			persister,
			subPath,
			propertyNumber,
			associationType,
			persister.getFetchMode( propertyNumber ),
			persister.getCascadeStyle( propertyNumber ),
			lhsTable,
			lhsColumns,
			nullable,
			currentDepth
	);
	addAssociationToJoinTreeIfNecessary(
			associationType,
			aliasedLhsColumns,
			alias,
			subPath,
			currentDepth,
			joinType
	);
}
 
Example #24
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Use an inner join if it is a non-null association and this
 * is the "first" join in a series
 */
protected JoinType getJoinType(boolean nullable, int currentDepth) {
	//TODO: this is too conservative; if all preceding joins were 
	//      also inner joins, we could use an inner join here
	//
	// IMPL NOTE : currentDepth might be less-than zero if this is the
	// 		root of a many-to-many collection initializer 
	return !nullable && currentDepth <= 0
			? JoinType.INNER_JOIN
			: JoinType.LEFT_OUTER_JOIN;
}
 
Example #25
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Count the number of instances of Joinable which are actually
 * also instances of PersistentCollection which are being fetched
 * by outer join
 */
protected static int countCollectionPersisters(List associations)
		throws MappingException {
	int result = 0;
	for ( Object association : associations ) {
		final OuterJoinableAssociation oj = (OuterJoinableAssociation) association;
		if ( oj.getJoinType() == JoinType.LEFT_OUTER_JOIN &&
				oj.getJoinable().isCollection() &&
				!oj.hasRestriction() ) {
			result++;
		}
	}
	return result;
}
 
Example #26
Source File: HqlSqlWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected AST createFromFilterElement(AST filterEntity, AST alias) throws SemanticException {
	FromElement fromElement = currentFromClause.addFromElement( filterEntity.getText(), alias );
	FromClause fromClause = fromElement.getFromClause();
	QueryableCollection persister = sessionFactoryHelper.getCollectionPersister( collectionFilterRole );
	// Get the names of the columns used to link between the collection
	// owner and the collection elements.
	String[] keyColumnNames = persister.getKeyColumnNames();
	String fkTableAlias = persister.isOneToMany()
			? fromElement.getTableAlias()
			: fromClause.getAliasGenerator().createName( collectionFilterRole );
	JoinSequence join = sessionFactoryHelper.createJoinSequence();
	join.setRoot( persister, fkTableAlias );
	if ( !persister.isOneToMany() ) {
		join.addJoin(
				(AssociationType) persister.getElementType(),
				fromElement.getTableAlias(),
				JoinType.INNER_JOIN,
				persister.getElementColumnNames( fkTableAlias )
		);
	}
	join.addCondition( fkTableAlias, keyColumnNames, " = ?" );
	fromElement.setJoinSequence( join );
	fromElement.setFilter( true );
	LOG.debug( "createFromFilterElement() : processed filter FROM element." );
	return fromElement;
}
 
Example #27
Source File: AbstractEntityPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected JoinType determineSubclassTableJoinType(
		int subclassTableNumber,
		boolean canInnerJoin,
		boolean includeSubclasses,
		Set<String> treatAsDeclarations) {

	if ( isClassOrSuperclassTable( subclassTableNumber ) ) {
		final boolean shouldInnerJoin = canInnerJoin
				&& !isInverseTable( subclassTableNumber )
				&& !isNullableTable( subclassTableNumber );
		// the table is either this persister's driving table or (one of) its super class persister's driving
		// tables which can be inner joined as long as the `shouldInnerJoin` condition resolves to true
		return shouldInnerJoin ? JoinType.INNER_JOIN : JoinType.LEFT_OUTER_JOIN;
	}

	// otherwise we have a subclass table and need to look a little deeper...

	// IMPL NOTE : By default includeSubclasses indicates that all subclasses should be joined and that each
	// subclass ought to be joined by outer-join.  However, TREAT-AS always requires that an inner-join be used
	// so we give TREAT-AS higher precedence...

	if ( isSubclassTableIndicatedByTreatAsDeclarations( subclassTableNumber, treatAsDeclarations ) ) {
		return JoinType.INNER_JOIN;
	}

	if ( includeSubclasses
			&& !isSubclassTableSequentialSelect( subclassTableNumber )
			&& !isSubclassTableLazy( subclassTableNumber ) ) {
		return JoinType.LEFT_OUTER_JOIN;
	}

	return JoinType.NONE;
}
 
Example #28
Source File: QueryTranslatorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Used for collection filters
 */
private void addFromAssociation(final String elementName, final String collectionRole)
		throws QueryException {
	//q.addCollection(collectionName, collectionRole);
	QueryableCollection persister = getCollectionPersister( collectionRole );
	Type collectionElementType = persister.getElementType();
	if ( !collectionElementType.isEntityType() ) {
		throw new QueryException( "collection of values in filter: " + elementName );
	}

	String[] keyColumnNames = persister.getKeyColumnNames();
	//if (keyColumnNames.length!=1) throw new QueryException("composite-key collection in filter: " + collectionRole);

	String collectionName;
	JoinSequence join = new JoinSequence( getFactory() );
	collectionName = persister.isOneToMany() ?
			elementName :
			createNameForCollection( collectionRole );
	join.setRoot( persister, collectionName );
	if ( !persister.isOneToMany() ) {
		//many-to-many
		addCollection( collectionName, collectionRole );
		try {
			join.addJoin(
					(AssociationType) persister.getElementType(),
					elementName,
					JoinType.INNER_JOIN,
					persister.getElementColumnNames( collectionName )
			);
		}
		catch (MappingException me) {
			throw new QueryException( me );
		}
	}
	join.addCondition( collectionName, keyColumnNames, " = ?" );
	//if ( persister.hasWhere() ) join.addCondition( persister.getSQLWhereString(collectionName) );
	EntityType elemType = (EntityType) collectionElementType;
	addFrom( elementName, elemType.getAssociatedEntityName(), join );

}
 
Example #29
Source File: AbstractEntityPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected JoinFragment createJoin(
		String name,
		boolean innerJoin,
		boolean includeSubclasses,
		Set<String> treatAsDeclarations) {
	// IMPL NOTE : all joins join to the pk of the driving table
	final String[] idCols = StringHelper.qualify( name, getIdentifierColumnNames() );
	final JoinFragment join = getFactory().getDialect().createOuterJoinFragment();
	final int tableSpan = getSubclassTableSpan();
	// IMPL NOTE : notice that we skip the first table; it is the driving table!
	for ( int j = 1; j < tableSpan; j++ ) {
		final JoinType joinType = determineSubclassTableJoinType(
				j,
				innerJoin,
				includeSubclasses,
				treatAsDeclarations
		);

		if ( joinType != null && joinType != JoinType.NONE ) {
			join.addJoin(
					getSubclassTableName( j ),
					generateTableAlias( name, j ),
					idCols,
					getSubclassTableKeyColumns( j ),
					joinType
			);
		}
	}
	return join;
}
 
Example #30
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<E> getByCriteriaWithAliasByOrder(Criterion criterion, String order, String[] orderBy, Integer count, String aliasTable, Criterion aliasCriterion) {
	Session session = getCurrentSession();
	List<E> fetchedList = new ArrayList<E>();
	//logger.info("Entity: " + entityClass + ", current Session = " + session);
	Criteria criteria = session.createCriteria(entityClass);
	criteria.add(criterion); 
	criteria.createAlias(aliasTable, aliasTable, org.hibernate.sql.JoinType.LEFT_OUTER_JOIN).add(aliasCriterion);
	if (orderBy != null) {
		for(int i = 0; i< orderBy.length; i++){
			if (order != null && order.equalsIgnoreCase("desc")) {
				criteria.addOrder(Order.desc(orderBy[i]));
			} else {
				criteria.addOrder(Order.asc(orderBy[i]));
			}
		}
	}
	if(count != null && count > 0){
		criteria.setMaxResults(count);
	}
	try {	
		fetchedList = criteria.list();
		return fetchedList;
	} catch (Exception e) {
		logger.error("getByCriteriaWithAliasByOrder failed, criteria = " + criterion.toString(), e);
		throw new HibernateException("getByCriteriaWithAliasByOrder failed, criteria = " + criterion.toString());
	}
}