【问题标题】:How do you implement Table Inheritance in Kotlin Exposed?你如何在 Kotlin Exposed 中实现表继承?
【发布时间】:2020-10-16 09:12:50
【问题描述】:

例子:

我有一个名为 Pet 的基表,其中包含 BirthDateName 列。

我还有两个从该表派生的表,一个称为 PetDog 表,列 NumberOfTeeth,另一个称为 PetBird 表,列 BeakColor

如何使用 Kotlin Exposed 实现这一点? https://github.com/JetBrains/Exposed

或者是否有任何可用的文档?

【问题讨论】:

  • PetDog 表应该有 3 列(BirthDateNameNumberOfTeeth)?或者它应该有 2 列(BirthDatePetId),其中PetId 指向Pet 表中的某行?

标签: kotlin kotlin-exposed


【解决方案1】:

您心目中的数据库和架构类型是什么?它如何支持表继承?正如评论中已经提到的Михаил Нафталь,关系数据库的一种常见方法是使用一个包含所有列的表或两个表(petdog,通过某种方式将两个表中的记录链接到彼此)。

两个表的简单示例:

create table pet (id int auto_increment primary key, birthdate varchar(10) not null, "name" varchar(50) not null)
create table dog (id int auto_increment primary key, pet_id int not null, number_of_teeth int not null, constraint fk_dog_pet_id_id foreign key (pet_id) references pet(id) on delete restrict on update restrict)

您的 Exposed 表定义代码可能如下所示:

object Pet : IntIdTable() {
    val birthdate = varchar("birthdate", 10)
    val name = varchar("name", 50)
}

object Dog : IntIdTable() {
    val petId = reference("pet_id", Pet).nullable()
    val numberOfTeeth = integer("number_of_teeth")
}

【讨论】:

  • 换句话说,使用组合而不是继承。但是,我不会使 Pet-reference 可以为空。 ;)
  • @TimvanderLeeuw 感谢您的评论,我同意。我已将 pet_id 更改为不可为空的字段。
猜你喜欢
  • 2020-10-17
  • 2021-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多