spring-data-relational icon indicating copy to clipboard operation
spring-data-relational copied to clipboard

Duplicate key column in selection

Open mivanus opened this issue 1 year ago • 2 comments
trafficstars

In some cases select statement contains duplicate key columns which causes BadSqlGrammarException when "order by" gets included in sql.

Code that causes duplication: https://github.com/spring-projects/spring-data-relational/blob/21e8d9a4fac7203f0f4d9a331b43e758ac47052c/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/SqlGenerator.java#L537-L539

mivanus avatar Apr 24 '24 15:04 mivanus

Please provide a Minimimal Reproducable Example, preferable as a Github repository. Make sure to include the database, either as an in memory database or if that is not possible using Testcontainers.

schauder avatar Apr 25 '24 07:04 schauder

I couldn't reproduce issue with H2 so i had to use Testcontainers+db2.

https://github.com/mivanus/spring-data-retional-issue-1779

mivanus avatar Apr 25 '24 10:04 mivanus

This might be related to #1680

I was able to reproduce this with DB2. Other databases don't throw an exceptions but still produce a select statement containing the same column twice in the select list.

For example:

SELECT 
  "BBB"."ID" AS "ID", 
  "BBB"."NAME" AS "NAME", 
  "BBB"."AAA_ID" AS "AAA_ID", 
  "ccc"."ID" AS "ccc_ID", 
  "ccc"."NAME" AS "ccc_NAME", 
  "ccc"."BBB_ID" AS "ccc_BBB_ID", 
  "BBB"."ID" AS "ID" 
FROM "BBB" LEFT OUTER JOIN "CCC" "ccc" ON "ccc"."BBB_ID" = "BBB"."ID" WHERE "BBB"."AAA_ID" = ? ORDER BY "ID"

schauder avatar May 06 '24 07:05 schauder

After some more investigation, there are a couple of things wrong with the mapping.

The relation between Aaa and Bbb is one internal to the aggregate of Aaa, but you use also AggregateTemplate.insert(bbb) which only works for aggregate roots. This does not work. See https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates

Also if Bbb is part of the Aaa aggregate, it needs a proper key-column holding the index of the Aaa.bbbs list. This is currently set to the "ID" which is the primary key of Bbb. Again, this does not work.

If you have further questions about fixing the mapping I recommend asking on SO. With the spring-data-jdbc tag, I will see and probably answer it.

If you think there is still an error with the SQL generation, please provide an updated reproducer. Otherwise this issue will be closed soon.

schauder avatar May 06 '24 12:05 schauder

If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.

spring-projects-issues avatar May 13 '24 12:05 spring-projects-issues

Closing due to lack of requested feedback. If you would like us to look at this issue, please provide the requested information and we will re-open the issue.

spring-projects-issues avatar May 20 '24 12:05 spring-projects-issues