Java Code Examples for org.hibernate.sql.JoinType#INNER_JOIN

The following examples show how to use org.hibernate.sql.JoinType#INNER_JOIN . 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: 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 2
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 3
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 4
Source File: BasicCollectionJoinWalker.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 {
	JoinType joinType = super.getJoinType(
			persister,
			path,
			propertyNumber,
			associationType,
			metadataFetchMode,
			metadataCascadeStyle,
			lhsTable,
			lhsColumns,
			nullable,
			currentDepth
	);
	//we can use an inner join for the many-to-many
	if ( joinType==JoinType.LEFT_OUTER_JOIN && path.isRoot() ) {
		joinType=JoinType.INNER_JOIN;
	}
	return joinType;
}
 
Example 5
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 6
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 7
Source File: IdentNode.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void resolveIndex(AST parent) throws SemanticException {
	// An ident node can represent an index expression if the ident
	// represents a naked property ref
	//      *Note: this makes the assumption (which is currently the case
	//      in the hql-sql grammar) that the ident is first resolved
	//      itself (addrExpr -> resolve()).  The other option, if that
	//      changes, is to call resolve from here; but it is
	//      currently un-needed overhead.
	if (!(isResolved() && nakedPropertyRef)) {
		throw new UnsupportedOperationException();
	}

	String propertyName = getOriginalText();
	if (!getDataType().isCollectionType()) {
		throw new SemanticException("Collection expected; [" + propertyName + "] does not refer to a collection property");
	}

	// TODO : most of below was taken verbatim from DotNode; should either delegate this logic or super-type it
	CollectionType type = (CollectionType) getDataType();
	String role = type.getRole();
	QueryableCollection queryableCollection = getSessionFactoryHelper().requireQueryableCollection(role);

	String alias = null;  // DotNode uses null here...
	String columnTableAlias = getFromElement().getTableAlias();
	JoinType joinType = JoinType.INNER_JOIN;
	boolean fetch = false;

	FromElementFactory factory = new FromElementFactory(
			getWalker().getCurrentFromClause(),
			getFromElement(),
			propertyName,
			alias,
			getFromElement().toColumns(columnTableAlias, propertyName, false),
			true
	);
	FromElement elem = factory.createCollection(queryableCollection, role, joinType, fetch, true);
	setFromElement(elem);
	getWalker().addQuerySpaces(queryableCollection.getCollectionSpaces());	// Always add the collection's query spaces.
}
 
Example 8
Source File: CriteriaQueryTranslator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public JoinType getJoinType(String path) {
	JoinType result = associationPathJoinTypesMap.get( path );
	return ( result == null ? JoinType.INNER_JOIN : result );
}
 
Example 9
Source File: FromElementFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
FromElement createElementJoin(QueryableCollection queryableCollection) throws SemanticException {
		FromElement elem;

		implied = true; //TODO: always true for now, but not if we later decide to support elements() in the from clause
		inElementsFunction = true;
		Type elementType = queryableCollection.getElementType();
		if ( !elementType.isEntityType() ) {
			throw new IllegalArgumentException( "Cannot create element join for a collection of non-entities!" );
		}
		this.queryableCollection = queryableCollection;
		SessionFactoryHelper sfh = fromClause.getSessionFactoryHelper();
		FromElement destination = null;
		String tableAlias = null;
		EntityPersister entityPersister = queryableCollection.getElementPersister();
		tableAlias = fromClause.getAliasGenerator().createName( entityPersister.getEntityName() );
		String associatedEntityName = entityPersister.getEntityName();
		EntityPersister targetEntityPersister = sfh.requireClassPersister( associatedEntityName );
		// Create the FROM element for the target (the elements of the collection).
		destination = createAndAddFromElement(
				associatedEntityName,
				classAlias,
				targetEntityPersister,
				(EntityType) queryableCollection.getElementType(),
				tableAlias
		);
		// If the join is implied, then don't include sub-classes on the element.
		if ( implied ) {
			destination.setIncludeSubclasses( false );
		}
		fromClause.addCollectionJoinFromElementByPath( path, destination );
//		origin.addDestination(destination);
		// Add the query spaces.
		fromClause.getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );

		CollectionType type = queryableCollection.getCollectionType();
		String role = type.getRole();
		String roleAlias = origin.getTableAlias();

		String[] targetColumns = sfh.getCollectionElementColumns( role, roleAlias );
		AssociationType elementAssociationType = sfh.getElementAssociationType( type );

		// Create the join element under the from element.
		JoinType joinType = JoinType.INNER_JOIN;
		JoinSequence joinSequence = sfh.createJoinSequence(
				implied,
				elementAssociationType,
				tableAlias,
				joinType,
				targetColumns
		);
		elem = initializeJoin( path, destination, joinSequence, targetColumns, origin, false );
		elem.setUseFromFragment( true );    // The associated entity is implied, but it must be included in the FROM.
		elem.setCollectionTableAlias( roleAlias );    // The collection alias is the role.
		return elem;
	}
 
Example 10
Source File: EntityJoinFromElement.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Ugh!
 */
@Override
public JoinFragment toJoinFragment(
		Map enabledFilters,
		boolean includeAllSubclassJoins,
		String withClauseFragment) throws MappingException {
	final String joinString;
	switch ( joinType ) {
		case INNER_JOIN:
			joinString = " inner join ";
			break;
		case LEFT_OUTER_JOIN:
			joinString = " left outer join ";
			break;
		case RIGHT_OUTER_JOIN:
			joinString = " right outer join ";
			break;
		case FULL_JOIN:
			joinString = " full outer join ";
			break;
		default:
			throw new AssertionFailure( "undefined join type" );
	}

	final StringBuilder buffer = new StringBuilder();
	final AbstractEntityPersister joinable = (AbstractEntityPersister) entityType.getAssociatedJoinable(factory);

	buffer.append( joinString );

	Set<String> treatAsDeclarations = getTreatAsDeclarations();
	final boolean include = includeAllSubclassJoins && isIncluded( entityTableAlias );
	String fromFragment = joinable.fromJoinFragment( entityTableAlias, true, include, treatAsDeclarations );
	String whereFragment = joinable.whereJoinFragment( entityTableAlias, true, include, treatAsDeclarations );

	// We need a table group only when having e.g. a left join of a polymorphic entity
	// fromFragment is empty if the entity is non-polymorphic
	// Inner joined entity joins can avoid using the table grouping since the condition can be moved to the where clause
	boolean renderTableGroup = !fromFragment.isEmpty() && joinType != JoinType.INNER_JOIN;

	if ( renderTableGroup ) {
		buffer.append( '(' );
	}

	buffer.append( entityTableText )
			.append( ' ' )
			.append( entityTableAlias );

	if ( renderTableGroup ) {
		buffer.append( fromFragment )
				.append( ')' );
	}

	buffer.append( " on " );

	final String filters = 	entityType.getOnCondition(
			entityTableAlias,
			factory,
			enabledFilters,
			Collections.<String>emptySet()
	);

	if ( fromFragment.isEmpty() || renderTableGroup ) {
		buffer.append( filters );
		if ( withClauseFragment != null ) {
			if ( StringHelper.isNotEmpty( filters ) ) {
				buffer.append( " and " );
			}
			buffer.append( withClauseFragment );
		}
	}
	else {
		// We know there is a fromFragment and that we shouldn't render a table group
		// This means the entity is polymorphic and the entity join is an inner join
		// We move the with clause stuff to the where clause but still need to have a valid on condition
		buffer.append( "1=1" );
		buffer.append( fromFragment );

		// Proper capacity to avoid resizing
		StringBuilder whereBuffer = new StringBuilder(
				10
					+ whereFragment.length()
					+ filters.length()
					+ withClauseFragment.length()
		);
		whereBuffer.append(whereFragment);
		if ( !filters.isEmpty() ) {
			whereBuffer.append( " and " );
			whereBuffer.append( filters );
		}
		if ( !withClauseFragment.isEmpty() ) {
			whereBuffer.append( " and " );
			whereBuffer.append( withClauseFragment );
		}

		whereFragment = whereBuffer.toString();
	}

	return new EntityJoinJoinFragment( buffer.toString(), whereFragment );
}