spring-projects / spring-data-relational

Spring Data Relational. Home of Spring Data JDBC and Spring Data R2DBC.

Home Page:https://spring.io/projects/spring-data-jdbc

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Invalid SQL generated when non-root entity in aggregate has a collection

jamoamo opened this issue · comments

If I have a nested entity aggregate where somewhere in the nest (not the root) there is a one-to-one relationship with a nested one-to-many relationship, the query from the one-to-many relationship entity will reference the incorrect column name. That sounds vague, even to me, so let me illustrate.

If I have a database structure such as below (imagine foreign keys from c -> b and b -> c):

CREATE TABLE a (a_id INT)
CREATE TABLE b (b_id INT, a INT)
CREATE TABLE c (c_id INT, b INT)

and entities for each table as follows (extraneous code excluded) where A contains a one-to-one relationship with B and B contains a one-to-many relationship with C.

public class C {
   @Id
   private int cId;
}

public class B {
   @Id
   private int bId;
   private Set<C> cChild;
}
public class A {
   @Id
   private int aId;
   private B bChild;
}

The above will result in an exception when querying the root of the aggregate using a repository bean along the lines of

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT "C"."C_ID" AS "C_ID" FROM "C" WHERE "C"."A_ID" = ?]

The generated SQL makes use of a column which does not exist in the table 'c' but only exists in table 'a'.

A workaround is to make the relationship between A and B to be a one-to-many relationship.

There is a minimalist project that reproduces the bug at https://github.com/jamoamo/spring-data-bug-reproducer

This looks similar to my reported issue #1739

It took some time for me to get redirected to spring-data-relational, so I'm just looking at already reported issues now.