【问题标题】:Modeling subclass/superclass while maintaining relational integrity在保持关系完整性的同时建模子类/超类
【发布时间】:2017-04-11 19:35:09
【问题描述】:

我试图在关系数据库中捕捉子类/超类关系的概念。如果我从

abstract class A {
   id: UUID
}

class B extends A {
    data: String
}

class C extends A {
    data: Int
}

我会写:

create table taba (id uuid not null unique, typ char not null);
create table tabb (id uuid not null unique references taba(id), 
          data varchar);
create table tabc (id uuid not null unique references taba(id),
          data int);

references 子句在一个方向上保证了它的关系完整性:每个派生实例 B 或 C 都必须有其基实例 A。

但是另一个方向呢?我想保证每个基本实例 A 都有其派生实例 B 或 C,并且理想情况下它与给定的 typ 匹配。

我想过在一个表中做,像这样:

create table taball (id uuid not null unique, typ char not null,
          b_data varchar,
          c_ data int);

但这似乎违反了open/closed principle:每次添加新的A子类时,我都必须重写taball。

我根本不知道这是否可能(特别是因为在实际插入过程中必然会违反完整性),但我希望有任何建议吗?

【问题讨论】:

  • 数据库用于组织和表示共享状态。对象应该封装状态并对其表示进行抽象,以专注于接口和职责。数据库用于状态,OOP 用于状态机。这两个概念是正交的,如果你把它们混为一谈,你都不会得到任何好处。

标签: sql postgresql relational-database


【解决方案1】:

PostgreSQL 支持 inheritance 用于表,因此您可以在数据库中执行与代码中完全相同的操作:

create table taba (id uuid not null unique);
create table tabb (data varchar) inherits (taba);
create table tabc (data int) inherits (taba);

这样,当您插入tabbtabc 时,taba 中也会有一行可用。这是否是一个好方法取决于具体情况。

【讨论】:

    猜你喜欢
    • 2010-09-28
    • 2010-09-24
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    相关资源
    最近更新 更多