@OneToMany(cascade = [ALL], orphanRemoval = true)
@JoinColumn(name = "optionId")
var options: MutableList<OptionVatiant> = mutableListOf()
After changes items of options field you may catch up an exception like this:
org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning
entity instance:
The cause is: you are setting a new collection via the setter thus leaving the original collection unreferenced by the Parent entity. It doesn’t work well with Hibernate and it doesn’t know what to do.
First solution is reuse exist collection by override the “set” method.
@OneToMany(cascade = [ALL], orphanRemoval = true)
@JoinColumn(name = "optionId")
var options: MutableList<OptionVatiant> = mutableListOf()
set(value) {
field.clear()
field.addAll(value)
}
Second solution is use not reassignable field ‘val’ for a collection.
@OneToMany(cascade = [ALL], orphanRemoval = true)
@JoinColumn(name = "optionId")
val options: MutableList<OptionVatiant> = mutableListOf()
options.add(option)
options.remove(option)