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.
Spring Data R2DBC applies familiar Spring abstractions and repository support for R2DBC. It makes it easier to build Spring-powered applications that use relational data access technologies in a reactive application stack. Spring Data R2DBC aims at being conceptually easy.
JPA cannot deal with reactive repositories such as provided by Spring Data R2DBC. This means you will have to do more things manually when using R2DBC. There are other reactive drivers around such as for example Quarkus Reactive Postgres client (which uses Vert.
Currently there are a few drivers ready for production, check the R2dbc drivers page for the complete list. H2 database is frequently used in development environment, add the following dependency when using either embedded or file-based H2 database.
Spring Data JDBC is an object-relational mapping framework for relational databases that aims to avoid most of the complexity of other ORM frameworks. It does that by avoiding features like lazy loading, managed lifecycles of entity objects and caching.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With