Search code examples
javajpakotlinone-to-manyhibernate-onetomany

How to tell JPA to manage dependent entities?


My model has a typical parent-children-relation which is JPA-modelled by an unidirectional @OneToMany relation:
a Parent has 0..n instances of Child (i.e. a List<Child>).

Trying to create and persist an Entity with one dependent Property as follows:

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

surprisingly results in

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).

at the line parentRepository.save(a_parent).

Obviously, JPA does not set the id of the parent on the child (column children.parent_id).

Why not? And how to tell it to do so?

The code of Parent and Child is as follows

@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
)

Solution

  • Unidirectional OneToMany may have to be implemented this way (reference):

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

    Pay attention to nullable = false if the database column parent_id is not nullable.