0

我正在使用 Spring Data 中的 CrudRepository 接口进行持久性,我想重置 OneToMany 关系中的子列表:清除所有现有子级并在同一个 save() 方法中附加新的子级

问题是子列表在从父对象中清除后似乎不为空,save 方法保留了旧子项和新子项之间的组合:得到一个与约束唯一性相关的错误:

父实体:

@Entity
@Table(name = "T_PRODUCT")
public class Product implements Serializable {

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Key> keys = new ArrayList<>();

    // Only getter method is available, no setter
    public List<Key> getKeys() {
        if (this.keys == null) {
            this.keys = new ArrayList<>();
        }
        return keys;
    }

}

子实体:

@Entity
@Table(name = "T_KEY", uniqueConstraints = {
    @UniqueConstraint(name = UIConstraintsConstants.UI_KEY_NAME, columnNames = { "NAME" }) })
public class Key implements Serializable {
    
    Column(name = "NAME", length = 100)
    private String name;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "FK_KEY_PRODUCT_ID", nullable = false, foreignKey = @ForeignKey(name = "FK_KEY_PRODUCT"))
    private Product product;

}

更新动作:

Product product = productRepository.findById(<id>).get();

// Update parent properties
product.setName("New name");
product.setDescription("New description");

// Clear the list of children linked to the parent
product.getKeys().clear();

// ⚠ I Need to perform a first save in order to clear the existing list of children, not a suitable way at all 
productRepository.save(product);

// Reset the list of children (same names but different details)
List<Key> keys = new ArrayList<>();
Key key1 = new Key("Key_01");
...
key1.setId(null);
key1.setProduct(product);

Key key2 = new Key("Key_02");
...
key2.setId(null);
key2.setProduct(product);

keys.add(key1);
keys.add(key2);
product.getKeys().addAll(keys);
productRepository.save(product);

当我尝试删除第一个保存时,我收到一个错误,例如(重复条目 'Key_01-1012' for key 'UI_KEY_NAME')证明旧的孩子没有被删除

如何使用一种保存方法重置儿童列表,在此先感谢!

4

0 回答 0