使用Spring Data JPA实现OneToMany集合的添加和删除操作。
示例实现:
// 定义OneToMany关联的实体类 @Entity public class Parent{
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
private List children;
public void addChild(Child child){
this.children.add(child);
child.setParent(this);
}
public void removeChild(Child child){
this.children.remove(child);
child.setParent(null);
}
}
@Entity public class Child{
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Parent parent;
// getter and setter are omitted.
}
// 在Controller中添加或删除Child @RestController public class ChildController {
@Autowired
private ParentRepository parentRepository;
@PostMapping("/parent/{parentId}/child")
public Child addChild(@RequestBody Child child, @PathVariable Long parentId){
Parent parent = parentRepository.getOne(parentId);
parent.addChild(child);
return child;
}
@DeleteMapping("/parent/{parentId}/child/{childId}")
public void removeChild(@PathVariable Long parentId, @PathVariable Long childId){
Parent parent = parentRepository.getOne(parentId);
Child child = parent.getChildren().stream()
.filter(c -> c.getId().equals(childId))
.findAny().orElseThrow();
parent.removeChild(child);
}
}
// ParentRepository
public interface ParentRepository extends JpaRepository