相关疑难解决方法(0)

如何在考虑可伸缩性和可测试性的同时将域实体正确地转换为DTO

我已经阅读了几篇文章和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)

java junit spring design-patterns spring-boot

20
推荐指数
4
解决办法
1万
查看次数

标签 统计

design-patterns ×1

java ×1

junit ×1

spring ×1

spring-boot ×1