Skip to content

Hibernate 7: compare two associations to unrelated classes by their identifiers, also where a part is an association - #17154

Open
borinquenkid wants to merge 13 commits into
fix/h7-subquery-root-alias-nested-paths-8.0.xfrom
fix/h7-compare-unrelated-association-ids-8.0.x
Open

borinquenkid wants to merge 13 commits into
fix/h7-subquery-root-alias-nested-paths-8.0.xfrom
fix/h7-compare-unrelated-association-ids-8.0.x

Conversation

@borinquenkid

Copy link
Copy Markdown
Member

Stacked on #16821, whose branch is the base of this one, so GitHub shows only this commit. It answers James's review of #16821, where two associations whose composite identifiers hold an association to unrelated classes were still compared as entities.

Problem

On Hibernate 7, eqProperty('leftRef', 'rightRef') of two associations to unrelated classes took one identifier out of each side. Where an identifier is composite and its first part is itself an association, those parts were then compared as entities and the query failed with Cannot compare left expression of type 'SpcOwnerA' with right expression ....

Change

PropertyComparisonCriterionHandler compares the two sides by their identifiers one part at a time, as Hibernate 5 does with the columns of the two foreign keys. A part that is itself an association is compared by the identifier of the associated entity, in turn one part at a time. Two identifiers with a different number of parts are not compared: the call throws an IllegalArgumentException that names both classes. An association compared with a value that is not an entity is still compared by its identifier. The call threw before, so no working code changes; the upgrade guide says so.

Tests

SiblingAssociationPropertyComparisonSpec has the sibling composite and generated identifiers, the mismatch, and two rows for composite identifiers that start with an association (through withCriteria and a detached criteria): both fail without the change. The Hibernate 7 module (5424 tests) passes, and so does codeStyle.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

…ir identifiers, also where a part is an association

eqProperty and neProperty of two associations whose classes are not related, such as eqProperty('left', 'right'), took
one identifier out of each side, which fails when the identifier is composite. Hibernate does not compare entities of
unrelated classes either, so the two sides are compared by their identifiers, one part for each property of a composite
identifier, as Hibernate 5 does with the columns of the two foreign keys. A part that is itself an association is
compared by the identifier of the associated entity, in turn one part at a time. An identifier of one property and an
identifier of two are not compared: the message names both classes. An association compared with a value that is not an
entity is still compared by its identifier.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@jamesfredley jamesfredley left a comment

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.

Requested changes. A comparison of two associations with different identifier shapes throws instead of matching nothing.

List<Expression<?>> leftParts = identifierParts(left, entityTypeOf(left));
List<Expression<?>> rightParts = identifierParts(right, entityTypeOf(right));
if (leftParts.size() != rightParts.size()) {
throw new IllegalArgumentException("Cannot compare [" + left.getJavaType().getName() + "] with [" +

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.

One association has a composite identifier and the other has a generated identifier. Comparing them should match no rows. It throws. Compare them without throwing, and match nothing when the identifiers differ.

…number of parts are never equal

Comparing an association with a composite identifier to one with a generated identifier threw an IllegalArgumentException. Identifiers of
different shapes are never equal, so == matches no row and != matches the rows that have both associations, as the comparison of their
foreign keys does on Hibernate 5.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley Fixed: two associations whose identifiers have a different number of parts no longer throw. Such identifiers are never equal, so eqProperty matches no row, and neProperty matches the rows that have both associations (a null stays unknown, as in SQL). SiblingAssociationPropertyComparisonSpec has the composite-id against generated-id case for eqProperty, neProperty, not { eqProperty } and a DetachedCriteria; the feature that expected the exception is replaced. The Hibernate 7 module and codeStyle pass.

@jamesfredley jamesfredley left a comment

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.

Requested changes. A comparison of two composite identifiers with different part types still throws.

List<Predicate> parts = new ArrayList<>();
for (int i = 0; i < leftParts.size(); i++) {
parts.add(negate ? criteriaBuilder.notEqual(leftParts.get(i), rightParts.get(i)) :
criteriaBuilder.equal(leftParts.get(i), rightParts.get(i)));

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.

One association has a composite identifier of text and text. The other has a number and text. Comparing them should match no rows. It throws, because only the number of parts is checked. Compare the part types too, and match nothing when they differ.

…r equal are not compared

Comparing two associations whose composite identifiers have the same number of parts but a text part against a number part threw, because
only the number of parts was checked. Identifiers that differ in the type of a part are never equal, as identifiers with a different number
of parts are, so eqProperty matches no row and neProperty matches the rows that have both associations. Numbers of different widths are
compared. SiblingAssociationPropertyComparisonSpec has the table for the criteria builder and a detached criteria; 6 of its rows fail
without the change.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley Fixed. Two identifiers whose parts have types that are never equal are not compared, as two with a different number of parts are not: eqProperty of such associations matches no row and neProperty matches the rows that have both. A part is compared with the part in the same position of the other identifier, so text against a number fails in any position, and numbers of different widths (Long against Integer) are compared as numbers.

The table in SiblingAssociationPropertyComparisonSpec runs eight rows through the criteria builder and through a detached criteria; six of the fifteen features fail without the change:

  • Part types: a composite of text and text against number and text (your case), against text and number (the second part differs), and Long and text against Integer and text (compared, equal and different rows).
  • Operators and shape: eqProperty, neProperty, not { eqProperty }, and an or of one comparison that is made and one that is never equal.
  • Data: an owner whose two associations are set and compare equal, ones that differ, and one with only one of them set.

Not covered, with the reason: gtProperty, ltProperty and the other ordering comparisons of two associations to unrelated classes are not part of this pull request, which is eqProperty and neProperty; an association part whose identifier has a different type than the one it faces (the identifier of a part that is itself an association) goes through the same check, but I did not give it a row of its own. The upgrade note is updated, and the Hibernate 7 module, codeStyle and the repository conventions pass.

@jamesfredley jamesfredley left a comment

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.

Requested changes. Two numeric identifier parts that are not the same value can still compare equal.

List<Predicate> parts = new ArrayList<>();
for (int i = 0; i < leftParts.size(); i++) {
parts.add(negate ? criteriaBuilder.notEqual(leftParts.get(i), rightParts.get(i)) :
criteriaBuilder.equal(leftParts.get(i), rightParts.get(i)));

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.

One identifier part is the long 9007199254740993. The other is the double 9007199254740992. They are not the same value. The row still matches, because the comparison rounds the long. Match nothing when the values differ.

@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed a3a23ba.

  • A composite id of text and text against one of a number and text: this matches no row for eqProperty and every row with both associations for neProperty, and it does not throw. It was fixed in the previous push (6791a2f) and SpcTextNum and SpcMixed in SiblingAssociationPropertyComparisonSpec hold it, in the criteria builder and in a DetachedCriteria.
  • The long 9007199254740993 against the double 9007199254740992: a database converts the integral part to compare it with a floating point one, which rounds a value a double cannot hold, so the two compared equal. An integral part against a floating point one is now refused with an IllegalArgumentException that names both types, and not compared. I chose a refusal over "match nothing" because 1 and 1.0 are the same value and would then never match; the two new rows (eqProperty and neProperty of a Long pair against a Double pair) fail without the change. The 8.0.1 upgrade note says so.

grails-data-hibernate7-core runs 5,434 tests green and codeStyle is clean.

@jamesfredley jamesfredley left a comment

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.

Requested changes. Two numeric identifier parts that are not the same value now throw instead of matching nothing.

boolean numbers = Number.class.isAssignableFrom(ClassUtils.resolvePrimitiveIfNecessary(left)) &&
Number.class.isAssignableFrom(ClassUtils.resolvePrimitiveIfNecessary(right));
if (numbers && floatingPoint(left) != floatingPoint(right)) {
throw new IllegalArgumentException("Cannot compare identifier parts of type " + left.getName() + " and " +

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.

One identifier part is the long 9007199254740993. The other is the double 9007199254740992. They are not the same value. Comparing them throws. Match nothing for equality, and match for inequality, without throwing.

@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed 33863aa. The long 9007199254740993 against the double 9007199254740992 no longer throws: eqProperty matches no row and neProperty matches the rows that have both associations. An integral part and a floating point one are treated like a text part against a number, as parts whose types are never equal: comparableTypes, PropertyComparisonCriterionHandler.java line 181, the rule at line 187. This replaces the refusal of the previous push.

One consequence you should know: it is a rule on the types, not on the values, so a Long part and a Double part that hold the same value, such as 1 and 1.0, do not match either. Comparing the values would depend on how each database converts the integral number, which rounds exactly the values that are the problem here; a composite identifier with a floating point part is rare enough that I chose the rule that cannot give a wrong match.

The test: SiblingAssociationPropertyComparisonSpec line 125, in the criteria builder and in a DetachedCriteria, with a row that has no second association; it fails without the change. grails-data-hibernate7-core runs 5,433 tests green and codeStyle is clean. The upgrade note is upgrading80x.adoc line 5055. Nothing in the guide defines identifier comparison across such parts.

@jamesfredley jamesfredley left a comment

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.

Requested changes. Two identifiers with the same leaf values are treated as different when an embedded part has a different class.

if (attribute instanceof SingularAttribute<?, ?> singular && singular.getType() instanceof EntityType<?> associated) {
parts.addAll(identifierParts(part, associated));
}
else {

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.

Two composite identifiers have the same leaf values and the same columns. One embedded part has a different class. Equality matches nothing, and inequality matches the row. Expand the embedded part and compare the leaves.

… of their embedded parts, whatever the classes of those parts are

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed d0519c7. An embedded part of a composite identifier is now compared by its leaves: PropertyComparisonCriterionHandler.addPart, line 231 expands an embedded value, at line 235, into its properties in the order of their names, as it already did for an association, so two embedded parts of different classes with the same leaves are the same columns and compare by value.

The test: SiblingAssociationPropertyComparisonSpec line 146, in a criteria builder and in a DetachedCriteria: one holder whose two identifiers have equal leaves in two classes (eqProperty matches it, neProperty does not) and one that differs in one leaf (the other way round). The entities are JPA entities with an @EmbeddedId that holds an @Embedded part (line 524 on): a GORM id composite cannot name an embedded property, the session factory does not build, so that is the form this case can take. Both rows fail without the change. grails-data-hibernate7-core runs 5,435 tests green and codeStyle is clean. Nothing in the guide defines identifier comparison across such parts.

@jamesfredley jamesfredley left a comment

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.

Requested changes. A negated comparison against a null association returns the row, and the same comparison without negation drops it.

if (!comparable(leftParts, rightParts)) {
// identifiers of different shapes are never equal: nothing matches ==, and every row that has both associations
// matches !=, a null being unknown as it is in SQL
return negate ? criteriaBuilder.and(criteriaBuilder.isNotNull(left), criteriaBuilder.isNotNull(right)) :

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.

For a row with a composite-id left and a null right that targets a single-id entity, not { eqProperty('left', 'right') } returns the row, but neProperty('left', 'right') excludes it. The fallback turns an unknown SQL result into false before negation. not { neProperty('left', 'right') } also returns the null row. A null association has to compare the same way in both forms.

…ison of identifiers that are never equal, as it is when they can be compared

When the identifiers of two associations cannot be compared, equality was a constant false and inequality required both associations,
so not { eqProperty } returned a row with a null association while neProperty and not { neProperty } treated it differently.
Each part of each side is now compared with itself, which is unknown for a null, so the comparison and every negation of it leave
the row out as SQL does for two columns.
…d-paths-8.0.x' into fix/h7-compare-unrelated-association-ids-8.0.x

# Conflicts:
#	grails-doc/src/en/guide/upgrading/upgrading80x.adoc
…L matches it, in every form of a comparison of two associations

A table over five pairs of associations, the four states of the two associations, five forms, including a negation nested in an or beside an isNull,
and the criteria builder and a detached criteria. Two older rows that required the rows with a null association from not { eqProperty }
are corrected to what the comparison of identifiers that can be compared returns.
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed the next commits, which answer the 12-04 finding: a row with a null association was matched differently by not { eqProperty } and by neProperty. You are right, and it was the fallback for identifiers that cannot be compared: equality was a constant false and inequality asked for both associations, and neither is unknown for a null, as it is in SQL. A negation of the first returned the row; the second and its negation did not agree with it.

Each part of each side is now compared with itself, and the parts are joined with or for equality (p <> p or q <> q ...) and with and for inequality (p = p and q = q ...). That is false (or true) when every part is there and unknown when one is not, so the comparison and every negation of it leave a row with a null association out, as the comparison of identifiers that can be compared does. I used every part, not the first, so an association whose key is partly null is unknown too.

The class, not the sample. SiblingAssociationPropertyComparisonSpec now generates 200 rows: five pairs of associations (composite with composite, composite with generated, text with mixed, text with number, long with int), the four states of the two associations (both there, left null, right null, both null), five forms (eqProperty, neProperty, not { eqProperty }, not { neProperty } and or { not { eqProperty }; isNull(right) }), on the criteria builder and on a detached criteria. The pairs of identifiers that can be compared (composite with composite and long with int) are controls for the path that already behaved this way. With the change reverted 44 rows fail.

Two older rows required the rows with a null association from not { eqProperty } (not { eqProperty('left', 'plainLeft') } expected mixed and no plain, and not { eqProperty('leftText', 'mixed') } expected the rows with a null as well). They encoded the behaviour you found, so I corrected them to mixed and texts, which is what the comparable path returns for the same rows.

grails-data-hibernate7-core passes (clean run) and codeStyle is clean. I merged the base branch again; the only conflict was upgrading80x.adoc, where I kept both sides. This runs on H2 only: x = x and x <> x are standard three-valued SQL, but I have not run the table on another database.

@jamesfredley jamesfredley left a comment

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.

Requested changes. A null association now compares the same way in both forms. Identifier parts the database treats as equal are still treated as unequal when their Java types differ.

// rounds a value that a double cannot hold, so two parts that are not the same value could compare equal
return floatingPoint(a) == floatingPoint(b);
}
return a.isAssignableFrom(b) || b.isAssignableFrom(a);

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.

A Character identifier 'x' and a String identifier "x" compare equal in SQL, and a LocalDate and a java.sql.Date that both map to DATE do too. This check uses Java assignability, so eqProperty matches nothing and neProperty matches the equal row. Use the mapped database type. Keep the numeric precision guard for values that are not exactly the same.

…mapped types

Two identifiers were taken for never equal when the Java classes of a part were not related, so a Character and a String, or a LocalDate and a java.sql.Date, which the
database compares as text and as a date, matched nothing for eqProperty and matched the equal row for neProperty. A part is now compared with another when the mapped
JDBC types are of one family: text, exact numbers, floating point numbers, dates and timestamps, times, booleans and binary values. An exact number and a floating point
one are still not compared, as the database converts the exact one and rounds a value that a double cannot hold, and a text and a number are not compared; a part without a basic
JDBC type, such as an enum or a UUID, is compared as before, by the relation of its Java classes. SiblingAssociationPropertyComparisonSpec has the 40 rows of five pairs of
types (Character and String, LocalDate and java.sql.Date, Integer and Long, Long and Double, String and Long), rows with the same value and with another, eqProperty and
neProperty, a criteria and a detached criteria; 8 of them fail with the previous comparison.
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed the next commit, which answers the review of 12-05 at b222b73. You are right, and it is the same decision that the earlier rounds each answered for one pair of types: whether two parts of identifiers can be equal is a question about the database, and I was answering it with the Java classes of the parts. A Character and a String are both text, and a LocalDate and a java.sql.Date are both a date, so for eqProperty I matched nothing and for neProperty I matched the equal row.

The rule now is the one you named: the mapped type. comparableParts takes the family of the JDBC type that the mapping gives each part, from the JdbcType of its BasicType (isStringLikeExcludingClob, isInteger or isDecimal, isFloat, isTemporal, isBoolean, isBinary): text, exact numbers, floating point numbers, dates and timestamps, times, booleans, binary values. Two parts are compared when they are of one family. The numeric precision guard stays as you asked: an exact number and a floating point one are different families, so a Long and a Double are never equal, since the database converts the exact one and rounds a value that a double cannot hold. A text and a number are different families too. A part with no basic JDBC type, such as an enum or a UUID, is compared by the relation of its Java classes, as before.

The table covers the class, not the two pairs of this review. SiblingAssociationPropertyComparisonSpec has 40 rows: five pairs of types (Character and String, LocalDate and java.sql.Date, Integer and Long, Long and Double, String and Long), a row whose two identifiers have the same value and one that has another, eqProperty and neProperty, and a criteria and a detached criteria. The expectation is computed in the spec from one statement of what a database does: the pairs it compares match when the values are equal, and the ones it does not compare match no row for eqProperty and the row for neProperty. With the comparison of the previous commit 8 rows fail, 4 for each of the two pairs of your review; the other 32, among them the pairs of the earlier rounds, pass with both.

grails-data-hibernate7-core passes and codeStyle is clean.

@jamesfredley jamesfredley left a comment

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.

Requested changes. Identifier parts the database treats as equal are still treated as unequal when their Java types differ.

Family leftFamily = familyOf(left);
Family rightFamily = familyOf(right);
if (leftFamily != null && rightFamily != null) {
return leftFamily == rightFamily;

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.

Composite identifiers (5L, 'x') and (5.0d, 'x') compare equal in SQL. eqProperty excludes the row and neProperty includes it. The check still rejects the pair by type family. Compare the values the database compares.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

3 participants