【问题标题】:Spring webflux convert Entity class to Mono DTO objectSpring webflux 将 Entity 类转换为 Mono DTO 对象
【发布时间】:2021-07-14 11:14:28
【问题描述】:

首先,我是 Spring webflux 的新手,并尝试在设置反应式 Spring Boot 项目时进行 POC。我有一个用例,我需要将检索到的实体类(PartyDTO)转换为 Mono 对象( Person :这是一个没有构造函数的第三方业务对象,我无法修改它)。我用谷歌搜索但无法找到与我的用例匹配的答案。

第 3 方对象:

  public class Person {
        // no constructors 
        private Integer custId;
        private String fullname;
        private LocalDate date;
        //
        getters and setters
    }

我的课程如下:

@Table("party")
public class PartyDTO {

    @Id
    private Integer party_id;
    private String name;
    private LocalDate start_date;
}

调用我的存储库的服务类。

 @Service
     public class ServiceImpl{

     @Override
        public Mono<Person> getParty(String partyId) {
            return 
    partyRepository.findById(Integer.parseInt(partyId)).flatMap(//mapper to convert PartyDTO to Person goes here);
        }
}

我尝试使用带有我的自定义映射器的平面图,如上所示,但它不起作用。有人可以建议我如何以非阻塞方式实现这一点(如果它支持非阻塞,第三方 bean 映射器也可以方法)

【问题讨论】:

    标签: java spring spring-boot spring-webflux spring-webclient


    【解决方案1】:

    假设 partyRepository.findById() 返回一个 Mono ,你可以简单地做

        @Service
             public class ServiceImpl{
        
             @Override
                public Mono<Person> getParty(String partyId) {
                     
           return partyRepository.findById(Integer.parseInt(partyId)).map(partyDto->{
             Person person = new Person();
             person.setName(partyDto.getName());
             return Mono.just(person);
    });
                }
        }
    

    可以参考https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#just-T-

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2018-07-26
      • 2022-01-11
      • 1970-01-01
      相关资源
      最近更新 更多