简体   繁体   English

替换双向一对多关系中的集合

[英]replace collection in bidirectional one-to-many relationship

Given the following JPA entities that have a bidirectional one-to-many relationship给定以下具有双向一对多关系的 JPA 个实体

@Entity
public class Cart {

    @OneToMany(mappedBy="cart")
    private Set<Items> items;
    
    // getters and setters
}

@Entity
public class Items {
    
    @ManyToOne
    @JoinColumn(name="cart_id", nullable=false)
    private Cart cart;
    
    // getters and setters
}

If I load a cart from the database that already contains some items如果我从已经包含一些项目的数据库中加载购物车

Cart cartWithItems = CartRepository.findById(cartId);

And I want to replace the items in this cart with a new collection of items我想用新的项目集合替换此购物车中的项目

Set<Item> newCartItems = ItemRepository.findAllById(newItemIds);

What is the simplest/best way to perform this replacement?执行此替换的最简单/最佳方法是什么? Ideally, I would like the generated SQL statements to be reasonably efficient, but my main goal is perform the replacement using code that's concise and readable.理想情况下,我希望生成的 SQL 语句相当高效,但我的主要目标是使用简洁易读的代码执行替换。

Update更新

Just to be clear about what I mean by replacement:只是为了清楚我所说的替换的意思:

If the cart initially contains items with IDs 2, 3, 4 and newItemIds contains 4, 5, 6, then after the replacement, the cart should contain items with IDs 4, 5, 6, and items with IDs 2, 3 should continue to exist (ie they should not be deleted).如果购物车最初包含 ID 为 2、3、4 的商品, newItemIds包含 4、5、6,那么替换后,购物车应包含 ID 为 4、5、6 的商品,ID 为 2、3 的商品应继续存在(即不应删除它们)。

I'd recommend adding orphanRemoval = true to your OneToMany annotation and then just remove the items from your cart.我建议将orphanRemoval = true添加到您的OneToMany注释中,然后从您的购物车中删除商品。 Furthermore I would recommend an add method that handles the bidirectional part like this:此外,我会推荐一种处理双向部分的add方法,如下所示:

public void addItem(Item item) {
  if(item != null) {
    this.items.add(item);
    item.setCart(this);
  }
}

You could also add a remove function if you wanted to.如果需要,您还可以添加remove function。 The addItem function could be used like this: addItem function 可以这样使用:

cartWithItems.setItems(new HashSet<>());
newCartItems.forEach(cartWithItems::addItem);

Hope this answers your question.希望这能回答您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM