房间实体和域模型,它们应该分开吗?

Edu*_*eda 8 architecture orm android

在我看来,许多关于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

}
Run Code Online (Sandbox Code Playgroud)

如果我把这个类变成了Room实体,我就不得不将我的对象引用改为外键,这实际上是不可能从这个类中进行我需要的计算.

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

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

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

这让我相信也许我完全错过了一些东西,或者我只是没有正确使用这些工具,这些案例有更好的选择吗?

tau*_*las 6

他们应该是分开的。

文档

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

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

然而,这种设计很可能违反单一职责原则,一旦您希望将数据保存在云中,数据可能会使用一些非 SQL 解决方案保存在云中,这种设计很快就会分崩离析。