Spring 如何用父亲的外键创建一个child

Spring how to create a child with the foreign key of the father

我的问题很简单,当我有 sku(产品的@id)时如何创建 Sale 实体?

Parent实体

public class Product {
   @Id
   private int sku;

   private String name;

   @OneToMany(mappedBy="product")
   private Set<Sale> sales;
}

Child实体

public class Sale {
   @Id
   @GeneratedValue
   private int id;

   @ManyToOne
   @JoinColumn(name="sku", nullable=false)
   private Product product;
   ...
}

通过id查找产品,使用数据创建销售,将产品设置为新销售,保存销售。假设 spring 数据和休眠,像这样:

Product product = productRepo.findById(id);
Sale sale = initWithData;
sale.setProduct(product);
saleRepo.save(sale);