Hibernate Create Update Delete child objects - Best way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
public class Parent implements Serializable { | |
@Id | |
@GeneratedValue(strategy = GenerationType.AUTO) | |
private Long id; | |
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true) | |
private Set<Child> children = new HashSet<>(); | |
... | |
} | |
@Entity | |
public class Child implements Serializable { | |
@Id | |
@GeneratedValue(strategy = GenerationType.AUTO) | |
private Long id; | |
@ManyToOne | |
@JoinColumn(name = "parent_id") | |
private Parent parent; | |
... | |
} | |
void processChildDto(Parent parent, Set<ChildDto> childDtos) { | |
Set<Child> children = new HashSet<>(); | |
for (ChildDto dto : childDtos) { | |
Child child; | |
if (dto.getId() == null) { | |
//CREATE MODE: create new child | |
child = new Child(); | |
child.setParent(parent); //associate parent | |
} else { | |
//UPDATE MODE : fetch by id | |
child = childRepository.getOne(dto.getId()); | |
} | |
BeanUtils.copyProperties(dto, child);//copy properties from dto | |
children.add(child); | |
} | |
parent.getChildren().clear(); | |
parent.getChildren().addAll(children); | |
//finally save the parent ( and children) | |
parentRepository.save(parent); | |
} | |