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

Time:06-03

My question is simply how do I create the Sale entity when I have the sku(@id of product)?

Parent Entity

public class Product {
   @Id
   private int sku;

   private String name;

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

Child Entity

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

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

CodePudding user response:

Find product by id, create a sale with data, set product in new sale, save sale. Assuming spring data and hibernate, something like this:

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