Den*_*søe 18 java orm hibernate jpa hibernate-mapping
我有一个我想要清除的@OneToMany集合(列表),并在同一个事务中添加新元素.
运用
collection.clear();
collection.add(new EntityB());
Run Code Online (Sandbox Code Playgroud)
只需添加新实例,永远不会删除任何内容.我有orphanRemoval = true收集领域.
添加:
// Parent entity
@OneToMany(mappedBy = "product", orphanRemoval = true)
private List<Feature> features = new ArrayList<>();
// Child entity
@ManyToOne(cascade = CascadeType.ALL)
private Product product;
// Clear and add attempt
product.getFeatures().clear();
Feature feature = new Feature(product, ls);
product.getFeatures().add(feature);
Run Code Online (Sandbox Code Playgroud)
Vla*_*cea 28
您尝试仅清除双向关联的一侧.
所以代替:
collection.clear();
Run Code Online (Sandbox Code Playgroud)
如本文所述,尝试清除双方,它应该工作:
for(Iterator<Feature> featureIterator = features.iterator();
featureIterator.hasNext(); ) {
Feature feature = featureIterator .next();
feature.setProduct(null);
featureIterator.remove();
}
Run Code Online (Sandbox Code Playgroud)
此外,从中删除级联@ManyToOne并将其移动到@OneToMany.
但是,如果您有唯一约束,则此clear + add反模式将不起作用,因为INSERT操作在DELETE操作之前执行,如本文中所述.
正确的方法是检查哪些条目需要删除,然后删除它们.然后,添加新的,并更新已修改的那些.这是您正确进行集合合并的方法.
事实证明,实际的解决方案是使用@JoinColumn 注释而不是mappedBy="" 参数。
| 归档时间: |
|
| 查看次数: |
18208 次 |
| 最近记录: |