Reputation: 5525
I'm using JPA/Hibernate over PGSQL DB.
I have an entity in my application, and I want to persist another entity (of a different type) every time the first entity is persisted. For example, whenever an "ORDER" is created, I want to immediately persist an empty "ORDER_INVOICE" entity and connect it to the order. These reside in two different tables.
At first I thought about writing a @PostPersist function for the ORDER entity and persisting the ORDER_INVOICE in it, but my problem is that I don't have the Entity Manager in this context.
I'm looking to avoid remembering to persist the ORDER_INVOICE upon every ORDER persistence.
Is that the right way to go? If so, how do I get the EM into the PostPersist? And if not, what would be a better way?
Upvotes: 3
Views: 1674
Reputation: 691755
Why don't you simply create it in the constructor of your master entity, and set cascade=persist on the relationship?
@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 each time the Order's constructor is invoked (by JPA, for example), you could use this kind of code :
@Entity
public class Order {
@OneToMany(mappedBy = "order", cascade=CascadeType.PERSIST)
private List<Invoice> invoices = new ArrayList<Invoice>();
/**
* Constructor called by JPA when an entity is loaded from DB
*/
protected Order() {
}
/**
* Factory method; which creates an order and its default invoice
*/
public static Order createOrder() {
Order o = new Order();
Invoice i = new Invoice();
i.setOrder(o);
o.invoices.add(i);
}
// ...
}
If the order is persisted after having been instanciated by the factory method, then the invoice will be persisted as well (thanks to the cascade). If the order is not persisted, then it will be garbage collected at some point, and its default invoide as well.
Upvotes: 3