如何将实体及其关系一起存储?

How to store an entity together with its relations?

想象以下实体:

@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

}

我创建了一个新的 Car 并向其中添加了一些新的 Tire。然后我试着救那辆车 使用 JpaRepository<Car, Long>save() 方法。汽车被坚持 但不是轮胎。我已经尝试将 cascade = CascadeType.PERSIST 添加到 @OneToMany 注释,但没有效果。那么如何存放轮胎呢?

您必须在 OneToMany 关系上设置 CascadeType