【发布时间】: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