Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
173e8a3
fix(hibernate7): keep the key of a unidirectional hasMany updatable u…
borinquenkid Oct 20, 2026
f2ea509
Merge remote-tracking branch 'origin/8.0.x' into fix/h7-multiple-hasm…
borinquenkid Oct 20, 2026
7138500
fix(hibernate7): count only collection-bound siblings when deciding w…
borinquenkid Oct 20, 2026
074284c
Merge remote-tracking branch 'origin/8.0.x' into fix/h7-multiple-hasm…
borinquenkid Oct 22, 2026
383c139
Hibernate 7: one scanner for the query package, and keep a spaced sql…
borinquenkid Oct 22, 2026
7c04569
Hibernate 7: read an HQL query once
borinquenkid Oct 22, 2026
ddbb8d0
Hibernate 7: an enum for the HQL keywords the reader looks for
borinquenkid Oct 22, 2026
e79032a
Hibernate 7: brackets group an expression unless they open an identif…
borinquenkid Oct 22, 2026
8b7515a
Hibernate 7: round-trip the shared join table through GORM, and docum…
borinquenkid Oct 23, 2026
e3c7fc7
Hibernate 7: read native SQL in the syntax of the database, resolved …
borinquenkid Oct 23, 2026
da0ef2b
Hibernate 7: read native SQL as each database lexes it, and HQL as Hi…
borinquenkid Oct 23, 2026
30586fc
Merge branch 'fix/h7-multiple-hasmany-8.0.x' into feat/sql-text-8.0.x
borinquenkid Oct 23, 2026
4aeaf4b
Merge branch 'fix/h7-multiple-hasmany-8.0.x' into feat/sql-text-8.0.x
borinquenkid Oct 23, 2026
a369f6b
Merge remote-tracking branch 'origin/8.0.x' into fix/h7-multiple-hasm…
borinquenkid Oct 23, 2026
c4e82e2
Hibernate 7: the count over a SQL projection no longer depends on how…
borinquenkid Oct 23, 2026
e394df9
Hibernate 7: a string in single quotes in a group by clause is a lite…
borinquenkid Oct 23, 2026
6333d95
Hibernate 7: pin that a literal in the group by clause reaches the SQL
borinquenkid Oct 23, 2026
d6b6da6
Merge branch '8.0.x' into fix/h7-multiple-hasmany-8.0.x
borinquenkid Oct 24, 2026
a928abb
Merge branch 'fix/h7-multiple-hasmany-8.0.x' into feat/sql-text-8.0.x
borinquenkid Oct 24, 2026
d3d2279
Merge pull request #16735 from apache/feat/sql-text-8.0.x
borinquenkid Oct 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
import org.grails.orm.hibernate.query.SqlGroupProjection;
import org.grails.orm.hibernate.query.SqlProjection;
import org.grails.orm.hibernate.query.SqlRestriction;
import org.grails.orm.hibernate.query.SqlSyntax;
import org.grails.orm.hibernate.support.hibernate7.SessionHolder;

/**
Expand Down Expand Up @@ -1183,7 +1184,7 @@ public ProjectionList sqlProjection(String sql, String columnAlias, Object type)
* @throws IllegalArgumentException if the numbers of projected values, column aliases and types differ
*/
public ProjectionList sqlProjection(String sql, List<String> columnAliases, List<?> types) {
for (SqlProjection projection : closingSessionOnError(() -> SqlProjection.of(sql, columnAliases, types))) {
for (SqlProjection projection : closingSessionOnError(() -> SqlProjection.of(sql, columnAliases, types, sqlSyntax()))) {
hibernateQuery.projections().add(projection);
}
return this;
Expand All @@ -1203,8 +1204,8 @@ public ProjectionList sqlProjection(String sql, List<String> columnAliases, List
* group by clause is empty
*/
public ProjectionList sqlGroupProjection(String sql, String groupBy, List<String> columnAliases, List<?> types) {
List<SqlProjection> projections = closingSessionOnError(() -> SqlProjection.of(sql, columnAliases, types));
for (SqlGroupProjection groupProjection : closingSessionOnError(() -> SqlGroupProjection.of(groupBy))) {
List<SqlProjection> projections = closingSessionOnError(() -> SqlProjection.of(sql, columnAliases, types, sqlSyntax()));
for (SqlGroupProjection groupProjection : closingSessionOnError(() -> SqlGroupProjection.of(groupBy, sqlSyntax()))) {
hibernateQuery.projections().add(groupProjection);
}
for (SqlProjection projection : projections) {
Expand Down Expand Up @@ -1248,10 +1249,15 @@ public org.grails.datastore.mapping.query.api.Criteria sqlRestriction(String sql
* or a value is {@code null}
*/
public org.grails.datastore.mapping.query.api.Criteria sqlRestriction(String sqlRestriction, List<?> values) {
hibernateQuery.add(new SqlRestriction(sqlRestriction, values));
hibernateQuery.add(closingSessionOnError(() -> SqlRestriction.of(sqlRestriction, values, sqlSyntax())));
return this;
}

/** The syntax of the native SQL of the database the session factory connects to, in which the DSL's SQL is read. */
private SqlSyntax sqlSyntax() {
return SqlSyntax.forSessionFactory(sessionFactory);
}

/**
* Creates a Criterion with from the specified property name and "rlike" (a regular expression
* version of "like") expression
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.Objects;

import org.hibernate.mapping.DependantValue;
import org.hibernate.mapping.Table;

import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyCollectionProperty;
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty;
Expand All @@ -39,19 +40,23 @@ public CollectionKeyColumnUpdater(CollectionKeyBinder collectionKeyBinder) {
public void bind(HibernateToManyProperty property) {
DependantValue key = collectionKeyBinder.bind(property);
key.getColumns().stream().filter(Objects::nonNull).forEach(column -> column.setNullable(true));
Table collectionTable = property.getCollection().getCollectionTable();
long unidirectionalCount = property.getHibernateOwner()
.getPersistentPropertiesToBind()
.stream()
.filter(HibernateToManyProperty.class::isInstance)
.filter(HibernateToManyProperty::isBoundAsCollection)
.map(HibernateToManyProperty.class::cast)
.filter(p -> !p.isBidirectional())
.filter(p -> Objects.equals(p.getCollection().getCollectionTable(), collectionTable))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This changes user-visible persistence. An owner with two unidirectional hasMany associations now writes the join table when each association has its own table, and still does not when they share one. That distinction is not in grails-doc or the GORM upgrade notes.

Please add a short public note: separate join tables are written; a shared join table is still the 10811 case and is not fixed by this change alone. A bugfix that changes which rows get written is a user-facing change and needs that coverage.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 8b7515a: section 26.11 of the Grails 8 upgrade notes says an owner with several unidirectional hasMany associations writes each join table of its own, as under Hibernate 5, and that two associations on one shared join table are read but not written, which is issue 10811 and not fixed by this change; the one-to-many chapter of the GORM for Hibernate 7 guide carries the same paragraph.

.count();

// Collections of basic values or enums (HibernateToManyCollectionProperty) always keep an updatable key: they
// have no inverse side, and Hibernate writes no rows for a collection whose key is not updatable.
// For entity collections (HibernateToManyEntityProperty) the key is non-updatable when the owner has two or
// more unidirectional to-many properties (counting every unidirectional HibernateToManyProperty of the owner),
// the existing rule for issue 10811.
// For entity collections (HibernateToManyEntityProperty) the key is non-updatable only when the owner has
// two or more unidirectional to-many properties that share this collection's join table, the rule for issue
// 10811. Unidirectional collections with join tables of their own keep an updatable key, as they have no
// second key column to leave null. A to-many that is not bound as a collection (a serializable or user type)
// has no join table and no Hibernate collection, so it is neither counted nor asked for one.
key.setUpdateable(property instanceof HibernateToManyCollectionProperty || unidirectionalCount <= 1);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.grails.orm.hibernate.dialect;

import org.hibernate.dialect.Dialect;

/**
* An enum whose constants each stand for the databases of some Hibernate dialects, so that one of them is chosen
* for the dialect a session factory connects with. A constant lists the dialect classes it is for; the one listing
* {@link Dialect} itself is the default, chosen for a dialect no other constant lists; a constant listing none is
* never chosen for a dialect. The constants are tried in their declared order, so a constant for a dialect
* subclass is declared before the constant for its superclass.
*
* @param <T> the enum
* @since 8.0.1
*/
public interface DialectKeyed<T extends Enum<T> & DialectKeyed<T>> {

/** The dialect classes the constant is for: the database of any of their instances. */
Class<? extends Dialect>[] dialectClasses();

/**
* Returns the constant of the enum for the dialect: the first whose dialect classes the dialect is an instance
* of, or else the first listing {@link Dialect} itself.
*
* @throws IllegalArgumentException if no constant is for the dialect and none is the default
*/
static <T extends Enum<T> & DialectKeyed<T>> T forDialect(Class<T> type, Dialect dialect) {
T fallback = null;
for (T candidate : type.getEnumConstants()) {
for (Class<? extends Dialect> dialectClass : candidate.dialectClasses()) {
if (dialectClass == Dialect.class) {
if (fallback == null) {
fallback = candidate;
}
} else if (dialectClass.isInstance(dialect)) {
return candidate;
}
}
}
if (fallback == null) {
throw new IllegalArgumentException(type.getName() + " has no constant for " + dialect.getClass().getName());
}
return fallback;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,14 @@ public class GrailsSqlProjectionFunction extends AbstractSqmSelfRenderingFunctio

public static final String NAME = "grails_sql_projection";

public GrailsSqlProjectionFunction() {
private final SqlSyntax syntax;

/**
* @param syntax the syntax of the native SQL of the database the session factory connects to
*/
public GrailsSqlProjectionFunction(SqlSyntax syntax) {
super(NAME, StandardArgumentsValidators.between(1, 2), new ImpliedTypeResolver(), null);
this.syntax = syntax;
}

@Override
Expand All @@ -67,7 +73,7 @@ public void render(
GrailsSqlRestrictionFunction.tableAlias(arguments.get(1)));
}
sqlAppender.appendSql(sql);
if (SqlRestriction.endsInLineComment(sql)) {
if (SqlText.of(sql, syntax).endsInLineComment()) {
sqlAppender.appendSql('\n');
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ public class GrailsSqlProjectionFunctionContributor implements FunctionContribut
public void contributeFunctions(FunctionContributions functionContributions) {
functionContributions.getFunctionRegistry().register(
GrailsSqlProjectionFunction.NAME,
new GrailsSqlProjectionFunction());
new GrailsSqlProjectionFunction(SqlSyntax.forDialect(functionContributions.getDialect())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,30 @@ public class GrailsSqlRestrictionFunction extends AbstractSqmSelfRenderingFuncti

static final String ALIAS_PLACEHOLDER = "{alias}";

private final SqlSyntax syntax;

/**
* @param typeConfiguration the type configuration of the session factory
* @deprecated since 8.0.1, the SQL is read in the syntax of the database: use
* {@link #GrailsSqlRestrictionFunction(TypeConfiguration, SqlSyntax)}, which this reads as {@link SqlSyntax#SQL}
*/
@Deprecated
public GrailsSqlRestrictionFunction(TypeConfiguration typeConfiguration) {
this(typeConfiguration, SqlSyntax.SQL);
}

/**
* @param typeConfiguration the type configuration of the session factory
* @param syntax the syntax of the native SQL of the database the session factory connects to
*/
public GrailsSqlRestrictionFunction(TypeConfiguration typeConfiguration, SqlSyntax syntax) {
super(
NAME,
StandardArgumentsValidators.min(1),
StandardFunctionReturnTypeResolvers.invariant(
typeConfiguration.getBasicTypeRegistry().resolve(StandardBasicTypes.BOOLEAN)),
null);
this.syntax = syntax;
}

@Override
Expand All @@ -75,7 +92,8 @@ public void render(
sql = sql.replace(ALIAS_PLACEHOLDER, tableAlias(arguments.get(1)));
firstValue = 2;
}
List<Integer> placeholders = SqlRestriction.placeholderIndexes(sql);
SqlText reading = SqlText.of(sql, syntax);
List<Integer> placeholders = reading.plainIndexes('?');
if (placeholders.size() != arguments.size() - firstValue) {
throw new IllegalArgumentException("The SQL restriction has " + placeholders.size() +
" ? placeholders but " + (arguments.size() - firstValue) + " values: " + sql);
Expand All @@ -89,7 +107,7 @@ public void render(
index = placeholder + 1;
}
sqlAppender.append(sql, index, sql.length());
if (SqlRestriction.endsInLineComment(sql)) {
if (reading.endsInLineComment()) {
sqlAppender.append('\n');
}
sqlAppender.append(')');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public class GrailsSqlRestrictionFunctionContributor implements FunctionContribu
public void contributeFunctions(FunctionContributions functionContributions) {
functionContributions.getFunctionRegistry().register(
GrailsSqlRestrictionFunction.NAME,
new GrailsSqlRestrictionFunction(functionContributions.getTypeConfiguration()));
new GrailsSqlRestrictionFunction(functionContributions.getTypeConfiguration(),
SqlSyntax.forDialect(functionContributions.getDialect())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@ public static Criteria sqlRestriction(AbstractDetachedCriteria<?> self, String s
* @param sqlRestriction the SQL condition
* @param values the values of the {@code ?} placeholders, in order, none of them {@code null}
* @return the detached criteria
* @throws IllegalArgumentException if the number of {@code ?} placeholders differs from the number of values,
* or a value is {@code null}
* @throws IllegalArgumentException if the SQL or a value is {@code null}. A number of {@code ?} placeholders that
* differs from the number of values is not reported here, since a detached criteria does not know the
* database, and so the syntax its SQL is read in, until it is executed on a connection; the query then fails
* with an exception whose cause is an {@code IllegalArgumentException}
*/
public static Criteria sqlRestriction(AbstractDetachedCriteria<?> self, String sqlRestriction, List<?> values) {
self.add(new SqlRestriction(sqlRestriction, values));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,20 +56,51 @@ public enum HibernateQueryArgument {
JOIN("join"),

// ── HQL keywords ──────────────────────────────────────────────────────────
// The reader of an HQL query uses HqlKeyword; these entries stay for anything that referenced them.
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_SELECT("select"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_FROM("from"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_WHERE("where"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_JOIN("join"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_LEFT("left"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_RIGHT("right"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_INNER("inner"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_OUTER("outer"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_GROUP("group"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_ORDER("order"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_HAVING("having"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_DISTINCT("distinct"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_ALL("all"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_AS("as"),
/** @deprecated since 8.0.1, the HQL keywords live in {@code HqlKeyword}; this entry is unused and goes in 9.0 */
@Deprecated(since = "8.0.1", forRemoval = true)
HQL_NEW("new"),

// ── Hibernate config properties ───────────────────────────────────────────
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.grails.orm.hibernate.query;

import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* The HQL keywords the reader of a query looks for, and which of them start a clause: a token after the root
* entity that starts a clause is the clause, not an alias of the entity.
*
* @since 8.0.1
*/
enum HqlKeyword {

SELECT("select", false),
FROM("from", false),
DISTINCT("distinct", false),
ALL("all", false),
AS("as", false),
NEW("new", false),
WHERE("where", true),
JOIN("join", true),
LEFT("left", true),
RIGHT("right", true),
INNER("inner", true),
OUTER("outer", true),
GROUP("group", true),
ORDER("order", true),
HAVING("having", true);

private static final Map<String, HqlKeyword> BY_TEXT = Stream.of(values())
.collect(Collectors.toUnmodifiableMap(HqlKeyword::text, Function.identity()));

private final String text;
private final boolean startsClause;

HqlKeyword(String text, boolean startsClause) {
this.text = text;
this.startsClause = startsClause;
}

/** The keyword in lower case, as the reader matches it against a lowercased query. */
String text() {
return text;
}

/** Whether a token, in any case, is a keyword that starts a clause. */
static boolean startsClause(String token) {
HqlKeyword keyword = BY_TEXT.get(token.toLowerCase(Locale.ROOT));
return keyword != null && keyword.startsClause;
}
}
Loading
Loading