Is it a good practice to use DTO in the service layer? [duplicate]

北城以北 提交于 2020-05-31 05:42:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!