问题描述
我的数据库中有两个聚合根实体,第一个是带有 Volunteer
和 Moderators
的 create table organizations
(
id uuid primary key default uuid_generate_v4(),name varchar(255) not null,slug varchar(64) not null unique
);
create table organization_moderators
(
id uuid primary key default uuid_generate_v4(),user_id uuid not null,organization_id uuid not null,is_owner boolean default false,unique (user_id,organization_id),foreign key (user_id) references users (id) on delete cascade,foreign key (organization_id) references organizations (id) on delete cascade
);
create table organization_volunteers
(
id uuid primary key default uuid_generate_v4(),foreign key (organization_id) references organizations (id) on delete cascade
);
。
表格:
@Value
@Table("organizations")
public class Organization {
@Id
@JsonIgnore
UUID id;
@Column("name")
String name;
@Column("slug")
String slug;
@MappedCollection(idColumn = "organization_id")
Set<Moderator> moderators;
@MappedCollection(idColumn = "organization_id")
Set<Volunteer> volunteers;
}
@Value
@Table("organization_moderators")
public class Moderator {
@Id
@JsonIgnore
UUID id;
@Column("user_id")
UUID userId;
@Column("is_owner")
boolean isOwner;
}
@Value
@Table("organization_volunteers")
public class Volunteer {
@Id
@JsonIgnore
UUID id;
@JsonIgnore
@Column("user_id")
UUID userId;
}
实体:
create table users
(
id uuid primary key default uuid_generate_v4(),username varchar(32) not null unique,email_address varchar(255) not null unique,password varchar(128) not null
);
其次,用户聚合根。
表格:
@Value
@Table("users")
public class User {
@Id
UUID id;
@Column("username")
String username;
@Column("email_address")
String emailAddress;
@Column("password")
String password;
}
实体:
User
对于我想做的查询,我想获取一个组织及其志愿者,并且我想在志愿者中包含用户表中的用户名。我将如何使用 Spring Data JDBC 做到这一点?我知道 Organization
不能成为 spreadsheet.setActiveRange('C' + +cellCount);
的聚合根的一部分,但这仍然是我想一次性查询的数据。
解决方法
我的第一个问题是:你为什么要这样做? 并不是说请求完全不合理,可能是在用户存储库中添加一些缓存更好解决。
但让我们假设我们同意您所要求的方式就是要走的路。
我看到了两种替代方法:
-
创建一个替代的组织聚合,其中包含直接引用
Volunteer
类的User
类的修改变体。重要的是永远不要试图保存这种Organization
。因此,我建议不要从CrudRepository
继承存储库,而只从Repository
继承存储库,并且只包含您实际需要的读取方法,而不包含写入方法。 -
您始终可以编写自定义
Query
和ResultSetExtractor
以完全按照您想要的方式加载数据。
记住 Spring Data JDBC 试图让一些事情变得简单,同时仍然允许您使用 JDBC 做任何您想做的事情。