Storing inherited objects in a database

后端 未结 3 1842
长情又很酷
长情又很酷 2021-01-06 06:05

I\'m trying to figure out the best way to map inheritance relationships in an object model into a relational database. For example consider the following class structure.

3条回答
  •  渐次进展
    2021-01-06 06:38

    You're describing Single-Table Inheritance, Concrete Table Inheritance, and Class Table Inheritance.

    See the classic Martin Fowler book Patterns of Enterprise Application Architecture for lots of information about them.

    One thing you can do to make sure only one sub-type can reference the super-type is to use an ItemType field. A foreign key can reference the columns of a UNIQUE constraint as well as a PRIMARY KEY. So you can add Items.ItemType and make a unique constraint over ItemID, ItemType. The foreign key in each sub-type table references this two-column unique key. And then you can constraint the ItemType in each sub-type table to be a certain value. Then it must match the value in the super-type table, which can only have one value.

    Items Table: ItemID (PK), ItemType, Name, Size
      UNIQUE: (ItemID, ItemType)
    Widgets Table: ItemID (PK), ItemType, Color
      FK: (ItemID, ItemType)
      CHECK: ItemType=W
    Doohicky Table: ItemID (PK), ItemType, Smell
      FK: (ItemID, ItemType)
      CHECK: ItemType=D
    

提交回复
热议问题