我有一个小问题,正确创建mathod将人员添加到团队。原因是我的问题是我无法在requestbody(或PathVariable)中添加两个参数。 我想带一个人身份和团队ID并返回两个连接。我创建了分隔的类,我生成id但我有问题从数据库中输入这个正确的id: 这是我在cotroller中的方法:
@PostMapping("/addPeopleToTeams/{teamId}/{personId}")
@ResponseBody
public String addPeopleToTeam(@RequestBody TeamsAndPersonsId teamsAndPersonsId){
System.out.println(" " + teamsAndPersonsId.getPersonId());
System.out.println(" " + teamsAndPersonsId.getTeamId());
teamService.findTeamById(teamsAndPersonsId.getTeamId());
personService.findById(teamsAndPersonsId.getPersonId());
return teamsAndPersonsId.getTeamId() + " " + teamsAndPersonsId.getPersonId();
}
这是我在服务中使用id查找的方法:
public Optional<TeamDto> findTeamById(Long id) {
Assert.notNull(id, "ID must exist ");
return teamRepository
.findById(id)
.map(p -> modelMapper.map(p, TeamDto.class));
}
其他我的班级是团队 - 这是实体,teamDto和TeamsAndPersonsId。
TeamsAndPersonsId class:
public class TeamsAndPersonsId {
private Long personId;
private Long teamId;
public TeamsAndPersonsId(Long personId, Long teamId) {
this.personId = personId;
this.teamId = teamId;
}
public TeamsAndPersonsId(){}
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
public Long getTeamId() {
return teamId;
}
public void setTeamId(Long teamId) {
this.teamId = teamId;
}
如何正确编写此控制器方法以返回真实团队和人员ID?就像我加入surce: @PostMapping( “/ addPeopleToTeams / {teamId} / {PERSONID}”
答案 0 :(得分:1)
您实际上可以使用多个路径变量,使用它们来创建TeamsAndPersonsId
,然后保留当前代码的其余部分:
@PostMapping("/addPeopleToTeams/{teamId}/{personId}")
@ResponseBody
public String addPeopleToTeam(@PathVariable Long teamId, @PathVariable Long personId){
TeamsAndPersonsId teamsAndPersonsId = new TeamsAndPersonsId(teamId, personId);
// etc...