Spring React中的实体对象到数据传输对象(DTO)

时间:2018-07-06 03:59:39

标签: java spring rx-java reactive-programming spring-webflux

我有订单模型

@Document(collection="order")
public class Order {
  @Id
  String id;

  String desc;

  String orgId;
}

每个OrgId都与组织对象相关联

@Document(collection="organization")
public class Organization {

    @Id
    String id;

    String desc;

    String ownerEmail;
}

我的订单DTO是

public class OrderDTO {

    String id;

    String desc;

    Organization org;

}

我想在Spring反应中返回Flux和Mono用于OrderDTO。

@RestController
@RequestMapping("orders")
public class OrderController {

    @Autowired
  private OrderService service;

    @Autowired
  private OrganizationService orgService;

    @GetMapping
    public Flux<OrderDTO> findAll() {
        return service.findAll(); // wanted step for Flux<Order> to Flux<OrderDTO>
    }

    @GetMapping("/{id}")
    public Mono<OrderDTO> findOne(@PathVariable String id) {
        return service.findOne(id); // wanted step for Mono<Order> to Mono<OrderDTO>
    }

}

1 个答案:

答案 0 :(得分:0)

首先尝试理清您的想法和步骤。

  1. 创建模型OrderOrganization
  2. 根据数据库的实现为每个模型创建存储库,将OrderRepositoryOrganizationRepository extends设为ReactiveMongoRepository或{ {1}}

    ReactiveCrudRepository
  3. 创建控制器端点

    import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface OrderRepository extends ReactiveMongoRepository<Order, String> {
       // Spring Boot automatically add  an implementation of this interface called SimpleOrderRepository at runtime.
    
      // So you get all the CRUD methods on the Document readily available to you without needing to write any code. Following are some of the methods available from SimpleReactiveMongoRepository -
    
      // reactor.core.publisher.Flux<T>  findAll(); 
      // reactor.core.publisher.Mono<T>  findById(ID id); 
      // <S extends T> reactor.core.publisher.Mono<S>  save(S entity); 
      // reactor.core.publisher.Mono<Void>   delete(T entity);
    
      // Notice that all the methods are asynchronous and return a publisher in the form of a Flux or a Mono type.
    }
    
    @Repository
    public interface OrganizationRepository extends ReactiveMongoRepository<Organization, String> {
    
    }
    

查看example和&doc以获取更多说明。