Answer the question
In order to leave comments, you need to log in
How to save a OneToMany collection so that its elements have a parent id?
I have a ControllCommand object that is filled entirely (along with the commands collection) from the @RequestBody from the controller. When saving it through session.save(), it is normally saved together with the collection to the database, but the elements of the collection do not have a foreign key (null).
Is there any easy way to fix this?
Or will you have to save the parent object first, then get its id, assign them to each element of the collection, and then save them?
@OneToMany(mappedBy = "command", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<CommandCondition> conditions;
@JoinColumn(name = "command_id")
@ManyToOne(fetch = FetchType.LAZY)
private ControlCommand command;
{"targetName":"hkuk,","action":0,"value":2,"conditions":[{"sensorName":"Включить","conditionType":0,"value":-1}]}
Answer the question
In order to leave comments, you need to log in
I decided on my own, in the end it turned out that in order for the elements of the collection to have an id, it was enough just to register a link to the parent itself for all of them. More or less like this:
command.getConditions().forEach(condition -> condition.setCommand(command));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question