首页 > 解决方案 > 如何使用端点将事物列表分配给另一个事物列表

问题描述

我有一个端点,它将角色列表分配给单个用户

@PutMapping(value = "/roles/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
public UserDto modifyRoles(
    @ApiParam(value = "User ID", required = true) @PathVariable("id") Long id,
    @ApiParam(value = "List of ID roles", required = true) @RequestBody List<Long> roles)
    throws someExceptions {
    return serviceClass.modifyUserRoles(id, roles);
}

我想收到一个用户列表以及一个角色列表,这样我就可以将每个角色分配给每个用户,但我不知道该怎么做,我是否应该通过@PathVariable 发送用户列表,或者如果我有一个更好的方法来做到这一点。这是我尝试过的:

@PutMapping(value = "/roles/{usersId}", consumes = MediaType.APPLICATION_JSON_VALUE)
public List<UserDto> modifyMultipleRoles(
    @ApiParam(value = "List of User ID", required = true) @PathVariable("id") List<Long> ids,
    @ApiParam(value = "List of ID roles", required = true) @RequestBody List<Long> roles)
    throws someExceptions {
    return serviceClass.newMethodThatAssignEachRoleToEachUser(ids, roles);
}

这是最好的方法吗?这甚至会起作用吗?

谢谢

更新响应

这是我现在尝试过的

List<Long> usersId=objectDto.getUsersId();
List<Long> rolesToAdd = objectDto.getRolesToAdd();
List<Long> rolesToDelete = objectDto.getRolesToRemove();
            
List<Usuario> users = usersId.stream()
                    .map(userId -> this.findById(userId))
                    .collect(Collectors.toList());
            
return users.stream().
// ????

那是继续的方式吗?

标签: javaspringrest

解决方案


最简单的方法是用相同的对象包装这些列表并将此对象用作 requestBody 参数:

public class UsersRolsRequest (){
    private List<Long> users;
    private List<Long> rols;
}

最终结果应该是这样的:

@PutMapping(value = "/roles/{usersId}", consumes = MediaType.APPLICATION_JSON_VALUE)
public List<UserDto> modifyMultipleRoles(@ApiParam(value = "Object with the list of ID 
        users and the List of ID roles", required = true) @RequestBody UsersRolsRequest 
        request)throws someExceptions {
    return serviceClass.newMethodThatAssignEachRoleToEachUser(ids, roles);
}

请求 json 将如下所示:

{
    "users": [1,2,3],
    "rols": [1,1,2]
}

推荐阅读