Kotlin 数据库的可空性 entities/objects 单独创建,但一起使用

Nullability of Kotlin database entities/objects created separately, but used together

我有两个数据库 类,带有 Hibernate/JPA 注释的计划和策略:

@Entity
@Table(name = "plan")
class Plan() : Idd {
    @get:Id
    @get:GeneratedValue(strategy = IDENTITY)
    @get:Column(name = "id", unique = true, nullable = false)
    override var id: Long = 0

    @get:ManyToOne(fetch = FetchType.LAZY)
    @get:JoinColumn(name = "top_strat_id", nullable = false)
    var topStrat: Strategy?
}

@Entity
@Table(name = "strategy")
class Strategy(
        @get:ManyToOne(fetch = FetchType.LAZY)
        @get:JoinColumn(name = "plan_id", nullable = false)
        var plan: Plan
) : Idd {
    @get:Id
    @get:GeneratedValue(strategy = IDENTITY)
    @get:Column(name = "id", unique = true, nullable = false)
    override var id: Long = 0
}

您可以看到有一个循环引用,其中每个 Strategy 都有一个 Plan,每个 Plan 都有一个 topStrat。我很确定我需要将计划持久保存到数据库中,以便它获得自动生成的 ID。然后我用我的计划创建一个新策略并保存它,以便它也获得一个自动生成的 ID。我需要让 Plan.topStrat 可以为空创建。

一旦创建,plan.topStrat 就永远不会再为 null(这是业务规则)。所以打电话给我的 Plan.topStrat 有点奇怪!!在六个地方。有没有一些简单的标准方法来处理这个问题?有什么我不知道的成语?

这发生在我使用的数据库中的几个地方。另一个例子是我们的用户 table 随着时间的推移获得了太多的列。我们将其拆分为 User 和 User2。用户在每个屏幕上都有所需的东西。 User2 拥有偶尔访问的内容。我需要将 User.user2 保留为 null 以创建用户并获取 ID。然后我想我实际上将 User2 的 ID 设置为与其相关的用户 ID 相等(因为它是 1:1)。保存后,User.user2 将永远不会再为 null。

这是一个极端案例,没什么大不了的。但如果有一些简单而优雅的方法来处理这个问题,我很想知道。

您应该可以使用 lateinit。尽管您需要注释 @field: 而不是 @get:,否则 JPA 提供程序将在尝试访问它时抛出。