2

I have 2 linked tables in the same aggregate but Spring Data JDBC does not use join for retrieving data. It does several Select requests instead, and I don't see why.

The tables:

TestA (aggregate root)
    idA (integer, PK)
TestB
    idB (integer, PK)
    idA (integer, FK -> TestA)

Entities:

@Data
public class TestA {
    @Id
    Integer idA;
    
    @MappedCollection(idColumn = "idA")
    Set<TestB> testBs = new HashSet<>();
}
@Data
public class TestB {
    @Id
    Integer idB;
}

Repository:

@Repository
public interface TestRepository extends CrudRepository<TestA, Integer> {
}

When calling testRepository.findAll(), it retrieves all the data and the objects are as expected (I have all the TestA with a list of associated TestB for each one), but it does it by requesting data from TestA, and then for each TestA line it requests TestB.

Executing prepared SQL statement [SELECT TestA.idA AS idA FROM TestA]
Executing prepared SQL statement [SELECT TestB.idB AS idB FROM TestB WHERE TestB.idA = ?]
Executing prepared SQL statement [SELECT TestB.idB AS idB FROM TestB WHERE TestB.idA = ?]
...

Why not a single Select with JOIN?? I guess I'm doing something wrong that is probably obvious, but I don't get it. For me and from my understanding it should be a left join or something like that, to retrieve in a single request data from TestA with the associated data from TestB.

bcassand
  • 41
  • 2

1 Answers1

1

No you are not doing anything wrong. This is just how Spring Data JDBC works right now.

The team is working on a new more efficient way to load aggregates, but it isn't ready yet.

If this is a problem for you you can specify your own query including a dedicated RowMapper or ResultSetExtractor in a @Query annotation.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • Could you make an example how to use `ResultSetExtractor` in a `@Query` annotation or point to the documentation where it explains how to do it? – Marco Lackovic May 12 '23 at 20:23