API平台OneToMany集合使用add/remove的问题
创始人
2024-09-08 01:00:59
0

使用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 { }

相关内容

热门资讯

重大发现(Wepoke俱乐部)... 重大发现(Wepoke俱乐部)外挂透明挂辅助器安装(透视)软件透明挂(存在有挂)-哔哩哔哩关于Wep...
我来向大家传授!微扑克app(... 我来向大家传授!微扑克app(wEpOke)外挂透明挂辅助app(辅助挂)详细教程(竟然有挂)-哔哩...
一分钟了解(WPK自建房)外挂... 一分钟了解(WPK自建房)外挂透明挂辅助插件(透视)软件透明挂(2022已更新)(哔哩哔哩)WPK自...
透明安装(WPK)外挂透明挂辅... 透明安装(WPK)外挂透明挂辅助app(辅助挂)软件透明挂(有挂教学)-哔哩哔哩1、许多玩家不知道W...
重要通知!pokermaste... 1、重要通知!pokermaster外挂(wePoke)外挂透明挂辅助挂(辅助挂)力荐教程(有人有挂...
终于懂了(线上德州aapoke... 1、终于懂了(线上德州aapoker)外挂透明挂辅助挂(辅助挂)透视辅助(2021已更新)(哔哩哔哩...
最新通报(pokernow德州... 最新通报(pokernow德州)外挂透明挂辅助神器(辅助挂)透视辅助(存在有挂)-哔哩哔哩是由北京得...
必备攻略!Wepoke德州局(... 必备攻略!Wepoke德州局(wePoke)外挂透明挂辅助神器(辅助挂)我来教教你(有挂教程)-哔哩...
科技通报(aapoker ap... 相信很多朋友都在电脑上玩过aapoker app吧,但是很多朋友都在抱怨用电脑玩起来不方便。为此小编...
科技通报(wepokeai代打... 科技通报(wepokeai代打)外挂透明挂辅助脚本(辅助挂)透视辅助(有挂详情)-哔哩哔哩;实战中需...