通过父实体更新删除添加子实体列表

lc8prwob  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(315)

有没有更好的方法 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;
}
dvtswwa3

dvtswwa31#

当你使用jpa的更新程序时,你可以让你的生活更轻松一些 orphanRemoval 功能,但要小心,因为它会导致您无意中删除内容:

父.java

@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);

相关问题