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.

Hantsy
  • 8,006
  • 7
  • 64
  • 109
  • 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. – Abhinaba Chakraborty Jul 18 '20 at 13:09
  • 1
    You can use a [functional interface](https://dzone.com/articles/you-dont-need-hibernate-with-spring-webflux-and-r2) to map results to multiple classes – Jani Sep 05 '20 at 15:49

1 Answers1

2

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.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • 3
    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... – nailer_boxer Jan 22 '23 at 15:18
  • Why does Spring R2DBC which literally stands for Reactive Relational Database Connectivity even exist if it doesn't support relationship mappings? – duppydodah Jul 25 '23 at 03:59