2017-10-19 108 views
0

节能战略在春季启动应用程序时,我们有儿童(一对多和cascade.all)列表的父实体,我们使用dto保存策略是什么?弹簧数据的JPA我们使用Hibernate实现</p> <p>DTO转换到实体JPA

我们必须循环子,与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 
    } 

} 

回答

1

只要在childsDto包含ID,你可以让他们童车的列表,然后在列表设置为。根据需要

例如为:

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

通过保存名单将被合并。

如果要删除那些没有父母了,你可以在家长添加orphanRemoval的关系,孩子的如下:

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

+0

作者:“只要childsDto包含id,你可以使他们成为Childs列表,然后将列表设置为父级,通过保存父级,列表将根据需要合并。”你的意思是采取每一个ID,做一个查询数据库,采取豆,更新字段... –

+0

我更新了答案,并希望它更清楚我的意思 – Tom

1

你可以有两种基本方式从您的DTO列表中筛选出重复项。

第一种方式

迭代通过您DTO列表和过滤掉重复的

方式二

使子组成在Parent实体Set像这样

@Entity 
class Parent { 

    ... 

    @OneToMany 
    Set<Child> children; 

    ... 

} 

现在在您的Child实体覆盖equalshashcode并定义您的Child实体是如何唯一的。这将迫使Set不是添加重复Child到您的Parent实体。

@Entity 
class Parent { 

    ... 

    @OneToMany 
    Set<Child> children; 

    ... 

}