Saving entity from parent to a child Spring boot

46 views Asked by At

Hello I am trying to understand how can I made a record in db with entity from another entity repository.

Example I have

public class Busstop {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "busstop")
private Bus bus;
}

Same for bus entity:

public class Bus {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "busstop_id", foreignKey = @ForeignKey(name = "fk_busstop_bus_id"))
private Busstop busstop;

Now when I call busstopService.save(busstop); I want to make a record also in bus table with the attached bus in the busstop dto with is not existing in the databse. Note: I don't want bus id to be present in the bbusstop table.

I am new to Spring boot.Thank you for the help

1

There are 1 answers

0
mikegrep On

I make a search online and I found that I need to use cascade = CascadeType.PERSIST on the@OneToMany mapping.