0

I'm implementing one-to-many relationship using Spring Data JDBC (1.0.10.RELEASE), where i.e. one Customer can have many Orders. When executing JOIN query I can see in DEBUG that after performing JOIN query, there are executed additional queries for each Order by its ID to get order data which seems completely redundant.

As a result when returning list of customers I get x results where x is a number of orders. So I get x customer objects which seem to be mapped fine (one-to-many relationship with orders also is mapped correctly), however they are repeated for each order.

Here is DB schema:

create sequence seq_customer start 1;

create table customer (
  id integer default nextval('seq_customer'),
  name varchar(100) not null,
  surname varchar(100) not null
  constraint pk_customer primary key (id)
);

create sequence seq_customer_order start 1;

create table customer_order (
  id integer default nextval('seq_customer_order'),
  customer_id integer not null,
  created_date timestamp not null,
  constraint pk_customer_order primary key (id),
  constraint fk_customer_order_id foreign key (customer_id) references customer (id)
);

When mapping foreign key in Customer class I use:

@Column("customer_id")
private Set<OrderEntity> orders;

Query:

@Query("SELECT * from customer c JOIN customer_order co ON c.id = co.customer_id")
List<Customer> findCustomers()

My question is, does Spring Data JDBC fully support JOINs?

Rafal
  • 1
  • 1

1 Answers1

0

As you noticed Spring Data JDBC loads aggregates with a 1:M relationship rather inefficiently.

If you provide a custom query the same RowMapper is used that is also used for the default methods, so the columns that come from your join are basically ignored and the additional selects are performed instead.

But you can provide your own RowMapper or in this case more useful ResultSetExtractor which will allow you to utilise the join.

See: https://github.com/spring-projects/spring-data-jdbc/blob/master/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/repository/query/Query.java#L56

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • I just noticed that this is not properly documented in the reference docuentation, so I created an issue for it: https://jira.spring.io/browse/DATAJDBC-429 – Jens Schauder Oct 07 '19 at 17:00
  • Thanks. I can see that ResultSetExtractor is available from 1.1.0 version only. I have difficulties with using spring-data-jdbc 1.1.0 with Spring Boot 2.1.8 - are these versions compatible or Spring Boot 2.2.0.RC1 is required? – Rafal Oct 09 '19 at 14:32
  • I recommend going with Boot 2.2.0.RC1 – Jens Schauder Oct 09 '19 at 15:25