Search code examples
postgresqlspring-bootspring-data-jdbcspring-data-r2dbcr2dbc

Best practice of handling relations between tables in Spring Data R2dbc


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.


Solution

  • 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.