【问题标题】:Converting dto to entity saving strategy in jpa在jpa中将dto转换为实体保存策略
【发布时间】:2017-10-19 12:55:44
【问题描述】:

在带有 spring data-jpa 的 spring boot 应用程序中,我们使用 hibernate 实现

当我们有一个包含子列表(一对多和 cascade.all)的父实体并且我们使用 dto 时,保存的策略是什么?

我们必须对child进行循环,与dto进行比较,如果有现有元素,则更新值,如果是新元素,则添加元素,如果已删除,则将其从列表中删除?

例子

Parent parent = repo.findById(Integer id);

//remove items who dont exit anymore
Childs childs = bean.getChild();
for (Iterator<Childs> iterator = childs.iterator(); iterator.hasNext();) {

    //compare with dto...

}


for (ChildsDto childsDto : ChildsDto) {

    if(childsDto==null){
        //add new element in the list of childs of parent
    }else{
        update element in the list of childs of parent
    }

}

【问题讨论】:

    标签: hibernate jpa spring-data-jpa


    【解决方案1】:

    只要 childsDto 包含 id,您就可以将它们设置为 Childs 列表,然后将该列表设置为 parent

    例如:

    List<Childs> childsFromDto = new ArrayList();
    for (ChildsDto childsDto : ChildsDto) {
    
    if(childsDto==null){
        //add new element in the list of childs of parent
    
    
        Childs child = new Childs();
        child.setId(childsDto.getId());
        ....
        childsFromDto.add(child);
    }
    parent.setChilds(childsFromDto);
    

    通过保存 parent,列表将根据需要合并。

    如果您想删除不再有父级的子级,您可以将 orphanRemoval 添加到 Parent 中的关系中,如下所示:

    @OneToMany(mappedBy=..., orphanRemoval="true") Collection<Childs> childs;

    【讨论】:

    • by "只要 childsDto 包含 id,您就可以将它们设置为 Childs 列表,然后将列表设置为父级。通过保存父级,列表将根据需要合并。"您的意思是获取每个 id,对数据库进行查询,获取 bean,更新字段...
    • 我更新了答案,希望我的意思更清楚
    【解决方案2】:

    您可以通过两种基本方法从DTO 列表中过滤掉重复项。

    第一种方式

    遍历您的 DTO 列表并过滤掉重复项

    第二种方式

    像这样在Parent 实体中将子组合设为Set

    @Entity
    class Parent {
    
        ...
    
        @OneToMany
        Set<Child> children;
    
        ...
    
    }
    

    现在在您的 Child 实体中覆盖 equalshashcode 并定义您的 Child 实体的唯一性。这将强制Set将重复的Child 添加到您的Parent 实体。

    @Entity
    class Parent {
    
        ...
    
        @OneToMany
        Set<Child> children;
    
        ...
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-22
      • 2018-09-14
      • 2013-07-26
      • 2016-06-10
      • 2019-05-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多