使用 Spring Data Jpa 保存相反实体时集合未更新

问题描述 投票:0回答:1

我有两个处于一对多关系的实体:

父实体:

@OneToMany(mappedBy = "parent")
public List<Child> getChildren()

子实体:

@ManyToOne
@JoinColumn(name = "PARENT_ID")
public Parent getParent()

考虑以下代码(事务内部):

Child child = childRepository.findById(id).get();
Parent parent = child.getParent();
child.setParent(null);
childRepository.saveAndFlush(child);
List<Child> children = parent.getChildren();

在这种情况下,“子”列表仍将包含子实体,尽管它已被删除。我尝试刷新存储库,保存父实体,甚至从parentRepository 获取一个新实体,但这些都不起作用。

为什么子列表在保存时未更新?如何在不显式删除实体的情况下确保集合是最新的(我想对集合中的实体进行进一步操作)?

spring jpa spring-data-jpa spring-data persistence
1个回答
0
投票

映射 @OneToMany 关联的最佳方法是依靠 @ManyToOne 端传播所有实体状态更改:双向 @OneToMany。

所以在你的情况下,父级应该如下所示

@OneToMany(mappedBy = "parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@Fetch(FetchMode.SELECT)
public List<Child> getChildren();

那么你必须添加以下方法

public void addChild(Child c){
   c.setParent(this);
   children.add(c);
}
public void removeChild(Child c){
   c.setParent(this);
   children.remove(c);
}

然后在事务方法中使用父存储库调用 saveAndFlush。

parentRepository.saveAndFlush(parent)
© www.soinside.com 2019 - 2024. All rights reserved.