Best practice of handling relations between tables in Spring Data R2dbc
Asked Answered
M

1

7

I tried to create a user/roles relation in RDBMS and want to use R2dbc(Spring Data R2dbc) to shake hands with the backend database.

Assume there are three tables, users, roles, and user_roles.

@Table("users")
class User {
    @Id
    private String username;

    private String password;

    private String email;

    @Builder.Default
    private boolean active = true;

    @Builder.Default
    private List<String> roles = new ArrayList<>();

    @Column("created_at")
    private LocalDateTime createdDate;

}

Unlike JPA, R2dbc reuses the spring-data-relational-common(which is also used in Spring Data Jdbc) to annotate the tables, but there is no facility to resolve the relations, such as the roles here.

Mahdi answered 11/5, 2020 at 9:34 Comment(2)
It is really confusing because the @MappedCollection comes with org.springframework.boot:spring-boot-starter-data-r2dbc:2.3.1.RELEASE . But using it in an entity with a collection variable fails.Peabody
You can use a functional interface to map results to multiple classesBrotherhood
S
3

Spring Data R2DBC currently does not support relationships.

So what you would do is to have a separate entity User2Role with two properties: String username and String rolename referencing the ids of the referenced entities.

Since you also tagged the question Spring Data JDBC: Spring Data JDBC does support 1:1 and 1:M references, but not M:1 or M:N relationships. See https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates for some background on that.

Spring Data R2DBC might eventually move to the same model.

Scaffolding answered 11/5, 2020 at 16:3 Comment(2)
Sorry for the tone, but when is the spring team going to work in that direction? This answer is almost 3 years old and nothing changed since then. This is a very frequent use case and there are no official guidelines how to deal with it...Vaporize
Why does Spring R2DBC which literally stands for Reactive Relational Database Connectivity even exist if it doesn't support relationship mappings?Kelila

© 2022 - 2024 — McMap. All rights reserved.