How to store an entity together with its relations?

70 Views Asked by At

Imagine the following entities:

@Entity
public class Car {

    @Id
    @GeneratedValue
    private long id;

    private String manufacturer;

    private String model;

    @OneToMany(mappedBy = "car")
    private Set<Tire> tires = new HashSet<>();

    // Getters & setters

}

@Entity
public class Tire {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne
    @JoinColumn(name = "car_id")
    private Car car;

    // Getters & setters

}

I create a new Car and add some new Tires to it. Then I try to save that car using the save() method of a JpaRepository<Car, Long>. The car gets persisted but not the tires. I already tried to add cascade = CascadeType.PERSIST to the @OneToMany annotation, but it had no effect. So how can I store the tires?

1

There are 1 best solutions below

2
On BEST ANSWER

You have to set CascadeType on the OneToMany relation.