Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sebCarabali/9fb9c6b57cd1542310f25f48ce2e6819 to your computer and use it in GitHub Desktop.
Save sebCarabali/9fb9c6b57cd1542310f25f48ce2e6819 to your computer and use it in GitHub Desktop.
@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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment