JPA: creating an object whenever another object is created

I am using JPA / Hibernate for PGSQL DB.

I have an entity in my application and I want to save another entity (of a different type) every time the first entity is saved. For example, whenever "ORDER" is created, I want to immediately save the empty ORDER_INVOICE object and connect it to the order. They are in two different tables.

At first I thought about writing the @PostPersist function for an ORDER object and storing ORDER_INVOICE in it, but my problem is that in this context I do not have Entity Manager.

I try to avoid remembering saving ORDER_INVOICE with every ORDER persistence.

Is this the right way? If so, how do I get EM in PostPersist? And if not, what would be the best way?

+3
source share
1 answer

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>();

    /**
     * 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 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.

+3
source

Source: https://habr.com/ru/post/1795204/


All Articles