https://kotlinlang.org logo
Title
r

roamingthings

02/07/2018, 5:15 AM
I’m looking for some kind of best practice how to model (bidirectional) JPA relations in Kotlin. I came up with the following solution but I’m not sure about the pros/cons. Especially when it comes to the mutability of the properties. Any suggestions?
@Entity
@Cacheable(false)
data class Person(
        @Id @GeneratedValue
        val id: Long? = null,

        @NotBlank
        val name: String
) {
    @OneToMany(mappedBy = "person", cascade = [(CascadeType.ALL)])
    var addresses: MutableSet<Address> = HashSet()
}

@Entity
@Cacheable(false)
data class Address(
        @Id @GeneratedValue
        val id: Long? = null,

        @NotBlank val address: String
) {
    constructor(address: String, person: Person): this(address = address) {
        this.person = person
    }

    @NotNull
    @ManyToOne(optional = false)
    lateinit var person: Person
}
d

dmulligan

02/14/2018, 5:39 PM
I have come across the same issue and never found a great solution. But what I have used init on the Person class to set the person on each item within the address list as follows.
init { addresses.forEach { it.person = this } }