I've 3 entities.
public class Masterpiece {
@Id
public Long id;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Product> products;
}
public class Product {
@Id
public Long id;
}
public class Purchase {
@Id
public Long id;
@OneToMany(fetch = FetchType.EAGER)
private List<Product> productList;
}
When I try to save Masterpiece with products, I get an error:
insertion or modification on the table "product" violates foreign key "fk_product_purchase_4" \ n Detail: Key (purchase_id) = (1) does not occur in the "purchase"
Im using ebean generated ddl.
You have two OneToMany relationship with Product, allright? Since you are creating a Masterpiece, then it will create a product. However, there is no Purchase object created in this case. According to this https://en.wikibooks.org/wiki/Java_Persistence/OneToMany (see Join Table topic), the other side (products, in this case) must has a back foreign key. In your problem it means a back reference foreign key to Masterpiece and Purchase, but Purchase does not exist when you create a Masterpiece and Product relationship. Maybe a solution is map it with ManyToOne back or using Join Table in your every OneToMany (Masterpiece and Purchase) achieving a separated tables for each relationship. I hope it can be useful!