Forked from gtiwari333/Hibernate Create Update Delete a List of child objects at once.java
Created
June 16, 2022 02:49
-
-
Save sebCarabali/9fb9c6b57cd1542310f25f48ce2e6819 to your computer and use it in GitHub Desktop.
This file contains hidden or 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); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment