我必须在我的应用程序中添加一个或多个用户角色。目前,我每次一个角色添加到用户使用这种方法:将角色添加到用户RESTful [Spring-Rest]
UserController.java
@RequestMapping(value = "users/{id}/{roleId}", method = RequestMethod.POST)
public User assignRole(@PathVariable Long id, @PathVariable Long roleId) throws NotFoundException {
log.info("Invoked method: assignRole with User-ID: " + id + " and Role-ID: " + roleId);
User existingUser = userRepository.findOne(id);
if(existingUser == null){
log.error("Unexpected error, User with ID " + id + " not found");
throw new NotFoundException("User with ID " + id + " not found");
}
Role existingRole = roleRepository.findOne(roleId);
if(existingRole == null) {
log.error("Unexpected error, Role with ID " + id + " not found");
throw new NotFoundException("Role with ID " + id + " not found");
}
Set<Role> roles = existingUser.getRoles();
roles.add(existingRole);
existingUser.setRoles(roles);
userRepository.saveAndFlush(existingUser);
log.info("User assigned. Sending request back. ID of user is " + id + existingUser.getRoles());
return existingUser;
}
此方法效果很好,但问题是:
- 的方法只能一次向一个用户添加一个角色
- 该方法不是RESTful
我的问题是:
如何添加一个或多个角色给用户的概念REST? 我应该甚至有一个特定的方法来为用户添加角色?或者我应该将角色添加到我的更新中的用户 - 方法PUT?