hibernate/hibernate-orm · error · IllegalArgumentException

Invalid query type provided to subquery 'with' method…

Error message

Invalid query type provided to subquery 'with' method, expecting a subquery with the same parent to use as CTE

What it means

IllegalArgumentException from SqmSubQuery.withInternal: the criteria passed to the subquery's with()/CTE method is either not a subquery or belongs to a different parent query.

Solutions

  1. Pass a subquery that has the same parent query as the one 'with' is called on.
  2. Create the CTE subquery via Subquery#with on a subquery obtained from the same parent, not an unrelated one.
  3. If the CTE belongs to the root query, register it on the root query's 'with' method instead.
Defensive patterns

Strategy: validation

When it happens

Trigger: An incompatible query (wrong parent or root query) is passed to a subquery's 'with' method for a CTE.

Common situations: Reusing a subquery from another parent as CTE; create the CTE subquery from the same parent.


AI-assisted analysis of hibernate/hibernate-orm@fad1729dce (2026-08-22). Data as JSON: /api/errors/c1fc9bb95c0db280. Report an issue: GitHub.

Appendix: source

Thrown at hibernate-core/src/main/java/org/hibernate/query/sqm/tree/spi/select/SqmSubQuery.java:212

				? cteContainer.getCteStatement( cteLabel )
				: cteCriteria;
	}

	@Override
	public <X> @Nullable JpaCteCriteria<X> getCteCriteria(@Nonnull String cteName) {
		final JpaCteCriteria<X> cteCriteria = super.getCteCriteria( cteName );
		return cteCriteria == null && parent instanceof JpaCteContainer cteContainer
				? cteContainer.getCteCriteria( cteName )
				: cteCriteria;
	}

	@Override
	protected <X> JpaCteCriteria<X> withInternal(String name, AbstractQuery<X> criteria) {
		if ( criteria instanceof SqmSubQuery<X> sqmSubQuery && sqmSubQuery.getParent() == parent ) {
			return super.withInternal( name, criteria );
		}
		else {
			throw new IllegalArgumentException(
					"Invalid query type provided to subquery 'with' method, " +
					"expecting a subquery with the same parent to use as CTE"
			);
		}
	}

	@Override
	protected <X> JpaCteCriteria<X> withInternal(
			String name,
			AbstractQuery<X> baseCriteria,
			boolean unionDistinct,
			Function<JpaCteCriteria<X>, AbstractQuery<X>> recursiveCriteriaProducer) {
		if ( baseCriteria instanceof SqmSubQuery<X> sqmSubQuery && sqmSubQuery.getParent() == parent ) {
			return super.withInternal( name, baseCriteria, unionDistinct, recursiveCriteriaProducer );
		}
		else {
			throw new IllegalArgumentException(
					"Invalid query type provided to subquery 'with' method, " +

View on GitHub (pinned to fad1729dce)