我已经阅读了几篇文章和Stackoverflow帖子,用于将域对象转换为DTO,并在我的代码中尝试了它们.在测试和可扩展性方面,我总是面临一些问题.我知道以下三种可能的域对象转换为DTO的解决方案.大部分时间我都在使用Spring.
解决方案1:服务层中用于转换的私有方法
第一种可能的解决方案是在服务层代码中创建一个小的"帮助器"方法,该方法将检索到的数据库对象转换为我的DTO对象.
@Service
public MyEntityService {
public SomeDto getEntityById(Long id){
SomeEntity dbResult = someDao.findById(id);
SomeDto dtoResult = convert(dbResult);
// ... more logic happens
return dtoResult;
}
public SomeDto convert(SomeEntity entity){
//... Object creation and using getter/setter for converting
}
}
Run Code Online (Sandbox Code Playgroud)
优点:
缺点:
new SomeEntity()在私有方法中使用,如果对象是深层嵌套的,我必须提供足够的结果,when(someDao.findById(id)).thenReturn(alsoDeeplyNestedObject)以避免NullPointers如果convertion也解散了嵌套结构解决方案2:DTO中用于将域实体转换为DTO的附加构造函数
我的第二个解决方案是在我的DTO实体中添加一个额外的构造函数来转换构造函数中的对象.
public class SomeDto {
// ... some attributes
public SomeDto(SomeEntity entity) {
this.attribute = entity.getAttribute();
// ... nesting convertion & convertion of lists and arrays …Run Code Online (Sandbox Code Playgroud)