在服务层中使用DTO是一种好习惯吗? [英] Is it a good practice to use DTO in the service layer?

查看:135
本文介绍了在服务层中使用DTO是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将dto转换为实体并将其传递到服务级别的控制器。

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));
    }

将正确的决定是转移到服务不是实体,而是转移到服务dto?
例如:

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);
}

在控制器级别转换实体和dto的决定是否正确? ?

And will the decision be correct to convert the entity and dto at the controller level?

推荐答案

将转换逻辑放在控制器中是一种不好的做法。所有转换/填充逻辑都应放在帮助器类中,例如转换器和填充器。在此处为例。

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.

此外,您的服务类应该为CRUD操作获得一个实体(而不是DTO),因为DTO可能不具有成功完成CRUD操作所需的所有值。但是,更好的做法是将所有CRUD操作都放到一个通用服务中,例如EntityService,并向其传递必须在其上执行CRUD操作的实体(例如,用户),例如YourEntityService.save(用户)。检查此处此处为例。

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.

这篇关于在服务层中使用DTO是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆