有没有更好的方法 add, update, delete
基于新传递的子实体列表的子实体(列表)?
我的更新功能
Parent parent = findById(id);
//make changes to parent attributes
//parent.setXyz(dto.getXyz());
//convert newly passed sons to hashmap
Map<String, Son> newSons = toHashMap(dto.getSons());
List<Son> finalSons = new ArrayList<>();
for (Son oldSon : parent.getSons()) {
if (newSons.containsKey(oldSon.getUniqueString())) {
finalSons.add(oldSon);
newSons.remove(oldSon.getUniqueString());
} else {
//Delete the son thats not in new list
sonRepository.delete(oldSon);
}
}
//add remaining sons
for (Son son : newSons) {
finalSons.add(son);
}
//existing.getSons().clear();
//existing.getSons().addAll(finalSons);
existing.getSons().clear();
parentRepository.save(parent);
父实体
@Entity(name = "parents")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Son> sons;
}
子实体
@Entity(name = "sons")
public class Son {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "parentId")
private Parent parent;
}
1条答案
按热度按时间dvtswwa31#
当你使用jpa的更新程序时,你可以让你的生活更轻松一些
orphanRemoval
功能,但要小心,因为它会导致您无意中删除内容:父.java
服务