E
E
Egor Lepikhin2020-02-27 19:34:11
Java
Egor Lepikhin, 2020-02-27 19:34:11

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?

ControlCommand
@OneToMany(mappedBy = "command", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<CommandCondition> conditions;

Command Condition
@JoinColumn(name = "command_id")
    @ManyToOne(fetch = FetchType.LAZY)
    private ControlCommand command;

Comes in @RequestBody
{"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

1 answer(s)
E
Egor Lepikhin, 2020-02-28
@LepikhinEgor

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 question

Ask a Question

731 491 924 answers to any question