Spring消耗Json并使用Hibernate返回值

时间:2018-10-05 09:42:11

标签: java json spring hibernate api

我有一个表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类?

2 个答案:

答案 0 :(得分:1)

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

在您的特定情况下,创建一个单独的CustomerSearchDto作为id的持有者也是多余的-最好仅与long s一起使用。

因此,只需在控制器中传递List<Long> ids作为参数(不要忘了将此参数注释为@RequestBody@RequestParam,具体取决于您要在哪里指定这些ID-在url或正文中),然后从您的服务类别中调用CrudRepository#findAll(ids)

答案 1 :(得分:0)

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