spring数据jdbc:非所有关系上的连接

iq0todco  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(334)

我的数据库中有两个聚合根实体,第一个是 OrganizationVolunteer 以及 Moderators .
table:

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(),
    user_id         uuid not null,
    organization_id uuid not null,
    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
);

实体:

@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;
}

对于我想做的查询,我想获取一个组织及其志愿者,对于志愿者,我想包括users表中的用户名。如何使用spring数据jdbc实现这一点?我理解 User 不能是的聚合根的一部分 Organization ,但这仍然是我想一次性查询的数据。

2admgd59

2admgd591#

我的第一个问题是:你为什么要这样做?这并不是说这个请求完全不合理,而是可以通过向用户存储库添加一些缓存来更好地解决这个问题。
但假设我们都同意你的要求。
我认为有两种方法可以做到这一点:
创建一个备用组织聚合,其中包含 Volunteer 引用 User 直接上课。重要的一点是永远不要试图挽救这种情况 Organization . 因此,我建议不要从中继承存储库 CrudRepository 但只能从 Repository 只包括你真正需要的阅读方法,不包括写作方法。
你总是可以写一首康斯通 Query 和一个 ResultSetExtractor 以您想要的方式加载数据。
记住springdatajdbc试图让一些东西变得简单,同时仍然允许您使用jdbc做任何您想做的事情。

相关问题