【问题标题】:Spring Consume Json and Return Value using HibernateSpring使用Hibernate消费Json和返回值
【发布时间】:2018-10-05 09:42:10
【问题描述】:

我有一个表 Customers 和 2 列 customer_id 和 customer_name。我想用 json 发送 id 列表请求并返回相应的客户名称。但我无法处理 dto 对象和控制器服务架构。

输入dto:

public class CustomerSearchDto extends BaseDto {
    @ApiModelProperty(
            example = "1",
            value = "Customer Id",
            required = true,
            dataType = "Long"
    )
    private Long id;
}

输出到:

public class CustomerDto extends BaseDto {

    private Long id;

    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

控制器类:

@ApiOperation(
            value = "Return Customer",
            response = Customer.class
    )
    @PostMapping(value = Endpoint.RRESOURCE_CUSTOMER_GROUP_BY_ID)
    public ResponseEntity<CustomerDto> getCustomersById(@RequestBody @Validated CustomerSearchDto CustomerSearchDto) {
        CustomerDto CustomerDto = new CustomerDto;
        List<CustomerDto> CustomerDtoList = CustomerService.findCustomerByIds(ids);
        return ResponseEntity.ok(CustomerDto);
    }

服务类方法:

@Transactional
    public List<CustomerDto> findCustomerByIds(List<Long> customerIds) {
        List<Customer> customerList = repository.findCustomerById(CustomerIds);
        return mapper.mapAsList(CustomerList, CustomerDto.class);
    }

控制器类有一些错误。而且我不确定是否应该为输入和输出定义不同的 dto 类?

【问题讨论】:

    标签: java json spring hibernate api


    【解决方案1】:

    首先,您似乎应该使用 CrudRepository#findAll(java.lang.Iterable&lt;ID&gt;) 通过多个 ID 搜索您的实体。

    此外,在您的特定情况下,创建一个单独的 CustomerSearchDto 作为 id 的持有者是多余的 - 最好只使用 longs。

    所以只需在控制器中将List&lt;Long&gt; ids 作为参数传递(不要忘记将此参数注释为@RequestBody@RequestParam,具体取决于您要在哪里指定这些ID - 在url 中或在正文中),然后调用CrudRepository#findAll(ids) 来自您的服务类。

    【讨论】:

    • 将 id 传递给服务后,我应该从控制器类返回什么?
    • customerDto customerDto = new customerDto; List customerDtoList = customerService.findcustomerIds(ids); return ResponseEntity.ok(customerDto);
    • 这里我没有使用customerDtoList。但如果我使用它返回则会发生错误。
    • 如果您成功找到客户 - 您应该返回 customerDtoList,如果您没有要返回的内容 - 您应该抛出异常“没有任何具有此类 id 的客户”或只返回空列表,具体取决于您的要求
    • 感谢@star67。你能举一个customerdtolist类的例子吗?我应该把什么方法放进去?
    【解决方案2】:

    您无需定义单独的输入和输出类,而是可以根据您的用例构建和返回 Map 或 List。同样对于输入,您可以接受列表,其中将包含您要检索的客户 ID 列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多