如何告诉 JPA 管理依赖实体?

How to tell JPA to manage dependent entities?

我的模型有一个典型的父子关系,它是通过单向 @OneToMany 关系进行 JPA 建模的:
Parent 有 0..n 个 Child 实例(即 List<Child>)。

尝试创建并保留一个 Entity 与一个依赖 Property 如下:

val a_parent = Parent(
        id = "I_am_a_parent",
        children = listOf(Child(kind="childish"))
)
parentRepository.save(a_parent)

令人惊讶的结果是

org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [parent_id]; nested exception is 
...
Caused by: org.postgresql.util.PSQLException: 
ERROR: null value in column "parent_id" violates not-null constraint
  Detail: Failing row contains (22, childish, null).

在第 parentRepository.save(a_parent).

显然,JPA 不会在子项(第 children.parent_id 列)上设置父项的 ID。

为什么不呢?以及如何告诉它这样做?

ParentChild的代码如下

@Entity
@Table(name = "parents")
data class Parent (
        @Id
        @Column(name = "id")
        var id: String? = null,

        @OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true)
        @JoinColumn(name = "parent_id")
        var properties: List<Child> = listOf()
)
@Entity
@Table(name = "children")
data class Child (
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        var id: Int? = null,

        @Column(name = "kind")
        var kind: String? = null
)

单向 OneToMany 可能必须以这种方式实现 (reference):

data class Parent (
  //...
    @OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true)
    @JoinColumn(name = "parent_id", nullable = false)
    var properties: List<Child> = listOf()
)

如果数据库列 parent_id 不可为空,请注意 nullable = false