I would state it is just a curiosity rather than an issue, but the point is next:
I have built a simple REST API using Spring Framework. There is no need to focusing on all the classes and interfaces implemented, so only the conceptional and logical model is mentioned infra.
1. To cut a long story short, let's say I have a basic User entity(auto-generated ID, name, email and password) and Role entity(auto-generated ID and its name). For both there also implemented Repository, Service and Controller with all CRUD operations included.
Used for the PUT method, the function for user update is following:
@Transactional
public void updateUser(Integer id, User user, Integer roleId) {
Role role = roleRepository.findById(roleId).get();
User userToUpdate = userRepository.findById(id).get();
userToUpdate.setName(user.getName());
userToUpdate.setEmail(user.getEmail());
userToUpdate.setPassword(user.getPassword());
userToUpdate.setRole(role);
userToUpdate.setDevices(user.getDevices());
userRepository.save(userToUpdate);
}
Although this code fragment is working correctly, it irritates and dismays me due to its step-by-step setters usage. The question is - are there any other options to simplify the excerpt given (for instance, some features of Stream API etc)?
2. And the second part of the question which is pretty connected to the previous extract. Here is another piece of code, responsible for the GET method to return all users with a specific role. But for the response entity, all the object are wrapped into the DTO prototypes with the ensuing program realization:
@GetMapping(value = "/roles/{roleId}/users")
public ResponseEntity<Set<UserDTO>> getUsersByRoleId(@PathVariable Integer roleId) {
Set<User> users = userService.getUsersByRoleId(roleId);
Link link = linkTo(methodOn(UserController.class).getAllUsers()).withSelfRel();
Set<UserDTO> userSet = new HashSet<>();
for (User entity : users) {
Link selfLink = new Link(link.getHref() + "/" + entity.getId()).withSelfRel();
UserDTO dto = new UserDTO(entity, selfLink);
userSet.add(dto);
}
return new ResponseEntity<>(userSet, HttpStatus.OK);
}
Again, do any different solutions exist to substitute that annoying "for loop"?
EDIT: I am not interested in some libraries/frameworks, but in a possible simplifications/alternatives using plain Java only