【问题标题】:Room entities and domain models, should they be separate?房间实体和域模型,它们应该分开吗?
【发布时间】:2019-05-29 11:17:56
【问题描述】:

在我看来,许多关于 Room(以及其他 ORM)的指南都专注于创建 Room 实体,并从那时起继续将它们用作他们的领域模型。但是如果我的模型需要它的实际结构来执行一些业务逻辑呢?

比如下面这个类:

class Report(var id: Long, var patient: Patient, var surgery: Surgery) {

    var minimumAllowableBloodLoss: Double = 0.0
        get() = ((this.patient.hemoglobin - this.patient.minHemoglobin) / this.patient.hemoglobin) * this.patient.bloodVolume * this.patient.weight
        private set

    var hourlyDiuresis: Double = 0.0
         get() = this.patient.diuresisOutput / this.surgery.duration
         private set

    var urineOutput: Double = 0.0
        get() = this.hourlyDiuresis / this.patient.weight
        private set

    var intakeSupply: Double = 0.0
        get() = this.patient.totalIntake / this.patient.weight
        private set

    var finalFluidBalance: Double = 0.0
        get() = this.patient.totalIntake - this.patient.totalOutput
        private set

}

如果我将这个类变成一个 Room 实体,我将不得不将我的对象引用更改为仅外键,这基本上使我无法从这个类中进行我需要的计算。

当然,我的第一直觉是完全放弃这个想法并创建一个表示对象,我相信它也被称为“持久模型”:

@Entity
data class ReportRow(
    var patientId: Long, var surgeryId: Long) {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
}

但这也意味着我必须创建从持久性模型到域的转换方法,反之亦然。

这让我相信也许我完全遗漏了一些东西,或者我只是没有正确使用这些工具,对于这些情况有更好的选择吗?

【问题讨论】:

  • FWIW 和恕我直言,对于大小合适的应用程序,实体和模型是分开的。这与让您的模型与您从 Web 服务获得的表示不同并没有显着不同。事实上,这就是进行分离的原因之一:您可能有 N 种加载和保存数据的方式(本地 + 网络),它们都不一定相同,并且其中任何一种都可能需要与您的首选不同内存中的表示。
  • 只是我的 2Cents,我到目前为止还不是专家,但我认为如果您将其分开,您将失去使用 Room 的应用程序架构的所有好处,例如 Single-Source-of-Truth 和 LiveData来自 DAO 的对象。

标签: android orm architecture


【解决方案1】:

它们应该是分开的。

来自docs

实体:表示数据库中的一个表。

尽管文档经常将实体称为“数据模型”,但许多示例简化了设计并假设实体 = 业务模型。

但是,这种设计很可能违反Single Responsibility Principle,并且一旦您希望将数据保存在云端(可能使用一些非 SQL 解决方案来保存数据),它很快就会崩溃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2023-04-02
    • 1970-01-01
    • 2020-12-07
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多