应该使用哪一层从域对象转换为DTO [英] Which layer should be used for conversion to DTO from Domain Object

查看:618
本文介绍了应该使用哪一层从域对象转换为DTO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用Spring Boot创建rest api.在我们的项目中,我们分为三层(存储库,服务和控制器).

We are creating rest api's with Spring Boot. We have three layers in our project(Repository, Service and Controller).

假设我的控制器中有GetUser api,该API返回UserDTO对象.

Lets say I have GetUser api in my controller that return UserDTO object.

@GetMapping
public UserDTO getUser() {
   return userService.getUser();    
}

userService.getUser()是返回UserDTO对象还是返回User对象并将其转换为控制器中的UserDTO对象?哪一种是更好的方法?

Whether userService.getUser() returns UserDTO object or it returns User object and it is converted to UserDTO object in the controller? Which one is better way?

简短地说,域对象到DTO对象的转换应该在服务层还是控制器层中完成?

Shortly, domain object to DTO object conversion, should be done in service layer or controller layer?

推荐答案

我认为没有将域对象转换为DTO对象的更好的方法",这是一个问题.在我的项目中,我将域对象转换为服务层中的DTO,这是我的业务逻辑"的一部分.因此,您减少了域对象仅对服务层的可访问性.此外,我想减少控制器内部的逻辑",因为它们是应用程序层的一部分.

I think there is no "better way" for converting your domain objects to your DTO objects, it's a matter of taste. In my projects I convert the domain objects to the DTO in the service layer as part of my "business logic". So you reduce the accessability of your domain objects only to your service layer. Furthermore I want to reduce the "logic" inside my controllers as they are part of the application layer.

PS:如果您正在寻找将域对象转换为DTO的几种方法,请查看我最新的Stackoverflow问题之一(

PS: If you are looking for several ways to convert your domain objects to your DTOs have look at one of my latest Stackoverflow questions (How to properly convert domain entities to DTOs while considering scalability & testability)

这篇关于应该使用哪一层从域对象转换为DTO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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