问题
I have a controller that converts dto to an entity and passes it to the service level.
@PostMapping(value = "/new", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserDto> create(@RequestBody UserDto userDto){
User newUser= userService.save(userMapper.userDtoToUser(userDto));
return ResponseEntity......body(userMapper.userToUserDto(newUser));
}
Will the correct decision be to transfer to the service not an entity, but a dto? For example:
public interface UserService{
UserDto save(UserDto userDto);
}
And will the decision be correct to convert the entity and dto at the controller level?
回答1:
This is a bad practice to put any conversion logic in the controller. All conversion/population logic should be put in helper classes e.g. converters and populators. Check here for an example.
Also, your service class should get an entity (and not DTO) for CRUD operations because the DTO may not have all the values required to complete the CRUD operation successfully. However, a better practice will be to put all the CRUD operations to a common service e.g. EntityService and to pass it the entities (e.g. User) on which CRUD operation has to be performed e.g. YourEntityService.save(user). Check here and here for an example.
来源:https://stackoverflow.com/questions/60307608/is-it-a-good-practice-to-use-dto-in-the-service-layer