I have a Spring
backend that is using Spring Data Rest
. I have a One-To-Many relation where the parent has its own repository but the children don't. I've chosen to do it this way because the child class is rather small and I would want to avoid having to make a bunch of requests to manage them.
So the classes are like this:
@Entity
class Parent(
@field:OneToMany(mappedBy="parent", cascade = [CascadeType.ALL])
var children: MutableList<Child> = mutableListOf()
)
@Entity
class Child(
@field:ManyToOne
var parent: Parent? = null
)
When I'm creating a parent, I post a JSON like this:
{
children: [
{ ... fields }
]
}
I have noticed that the child entities are indeed created but the field referencing the parent is not populating. To overcome this, I've tried to set the parent field in a @PrePersist
and @PreUpdate
method. This worked for a while but then I've noticed that the fields are not deleted when I make a patch request and don't include them in the JSON. Google-in a bit a found that the orphanRemoval
property of the @OneToMany
relation can be the key but when I've added it, the first part of my problem (populating the relationship fields) stoped working.
Is there a way to handle these operations with Spring Data Resp
to avoid having to write a custom controler from scratch?
EDIT:
Turns out they are not connected. My @PreUpdate hooks are not called because Spring does not save my entity if there were no changes to its fields. Can this behaviour be altered somehow (again, without creating a custom controller)