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

Implicit join on one-to-many relations

Open petromir opened this issue 3 years ago • 2 comments

I really like the simplicity of spring-data-jdbc, but the default behaviour somehow breaks my understanding of efficient loading.

Problem description Having one-to-many relations in an aggregate root always causes N+1 queries. There is no way to change this so if I have the following structure, I end up with many redundant SQL statements.

Minion

class Minion {
	@Id
	Long id;
	String firstName;
	String lastName;
	@MappedCollection(idColumn = "minion_id", keyColumn = "id")
	final Set<Toy> toys = new HashSet<>();
}

Toy

class Toy {
	@Id
	Long id;
	String name;
	Long minionId;
}

Expected behaviour Change the default behaviour and load all the relations with implicit join. I assume that the library has the information

Environment org.springframework.boot:spring-boot-starter:2.5.6 org.springframework.boot:spring-boot-starter-data-jdbc: 2.5.6 org.springframework.data:spring-data-jdbc:2.2.6

petromir avatar Sep 19 '22 08:09 petromir

We are working on a more efficient way to load aggregates.

schauder avatar Sep 19 '22 12:09 schauder

@schauder Is there another ticket related to this activity?

petromir avatar Sep 27 '22 07:09 petromir

I ended up with the same realisation after turning on sql trace.

Meanwhile what could be done, is using a projection with a custom query.

This help prevent the loading of one-to-many relationship, which help make the system more responsive

benzen avatar Nov 25 '22 19:11 benzen

@petromir Found this ticket which was created in 2019 https://github.com/spring-projects/spring-data-relational/issues/592

benzen avatar Nov 29 '22 19:11 benzen

duplicate of #592

schauder avatar Nov 30 '22 08:11 schauder