JPA with JTA: Persist entity and merge cascaded child entities

前端 未结 4 1623
情歌与酒
情歌与酒 2020-12-20 11:21

I have a bidirectional one-to-many relationship with the following entity classes:

0 or 1 client <-> 0 or more product orders

When persis

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 11:50

    @SputNick ,I solved it by the steps described below.I am going to use your code snippet to demonstrate what I did,

    You have Client entity -@OneToMany and ProductOrder entity -@ManyToOne .I will use

    // Called when pressing "save" on the "edit..." 
    public void edit(T entity) {
     getEntityManager().merge(entity);}
    

    for persistence as it can give me flexibility to save as well as update.

    To create Client and corresponding Product orders use

    client.set..(some property to be saved);
    
    productOrder.set..(some property to be saved);
    

    //Set productOrder for the client

    List order = new ArrayList<>();
    

    client.setOrders(order); //Note that this expects a list to be passed

    //set client for the productOrder

    productOrder.setClient(productOrder);
    
    .edit(client) or .edit(productOrder)
    

    Note that either way will be able to update both entity tables with your changes.

    Though late,hope it will help someone

提交回复
热议问题