Is there a better way to add, update, delete
child entities (LIST) based on the newly passed list of children?
My updated function
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);
Parent entity
@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;
}
Child entity
@Entity(name = "sons")
public class Son {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "parentId")
private Parent parent;
}
You could make your life a bit easier regarding to the updating process when you make use of JPA's orphanRemoval
feature, but beware because it can result in you deleting stuff involuntarily:
@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, orphanRemoval = true)
private List<Son> sons;
}
Parent parent = findById(id);
Map<String, Son> addedSons = toHashMap(dto.getSons());
// Remove existing sons that are not part of the update
parent.getSons().removeIf(existingSon -> !addedSons.containsKey(existingSon.getUniqueString()));
// Add new sons
addedSons.forEach(parent.getSons()::add);
// Save parent and trigger creating of added sons/deletion of removed existing sons
parentRepository.save(parent);