Why don't you just create it in the constructor of your main entity and set cascade = persist in relation?
@Entity
public class Order {
@OneToMany(mappedBy = "order", cascade=CascadeType.PERSIST)
private List<Invoice> invoices = new ArrayList<Invoice>();
public Order() {
Invoice i = new Invoice();
i.setOrder(this);
this.invoices.add(i);
}
}
EDITED:
To avoid creating a new invoice every time the Order constructor is called (for example, JPA), you can use this kind of code:
@Entity
public class Order {
@OneToMany(mappedBy = "order", cascade=CascadeType.PERSIST)
private List<Invoice> invoices = new ArrayList<Invoice>();
protected Order() {
}
public static Order createOrder() {
Order o = new Order();
Invoice i = new Invoice();
i.setOrder(o);
o.invoices.add(i);
}
}
If the order is saved after it has been called by the factory method, then the invoice will be saved (thanks to the cascade). If the order is not saved, then it will be collected at a certain point, and its default value will also be displayed.
source
share