-
-
Save gtiwari333/8db9d5e4acf3dd17ea9bd65b22735eec 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); | |
} | |
It will just work. Try it yourself. Hibernate is smart enough to figure out which record needs to be deleted, inserted or updated
if you make clear list - i try it - you will clear all rows from database and create another rows and this is what i don't want to do i want to update only the existing and add the new and delete something if i want to delete
Your code efficiently processes ChildDto
objects for a Parent
, handling creation and updates. Consider using findById
instead of getOne
for safer fetching, and explore saveAll
for batch operations. This enhances readability and ensures robustness in entity retrieval and persistence gamers! I just wanted to let you know about the amazing casino bonuses Canada has to offer. As a first-time player, I was blown away by the list of casinos that are offered at https://bestcasinoplay.com/online-slots/bonuses/ deposit match, free cash, and even those amazing free spins. It’s a great way to start your gaming journey right after you sign up. And what’s more – the goodness doesn’t end there! For existing players, you can enjoy reload bonuses as well as cash-back benefits.
Wont this fail when we have an update item and a add time in the request list? The previous list will get cleared using
parent.getChildren().clear();
and will be replaced by entirely new list, clearing all previous items. How can we handle a scenario in which we need to persist with a few items and update the rest?