Java Spring使用Hibernate使用Json并返回值
我有一个表Customers和两列customer\u id和customer\u name。我想用json发送id列表请求,并返回相应的客户名称。但我无法处理dto对象和控制器服务架构 输入dto:Java Spring使用Hibernate使用Json并返回值,java,json,spring,hibernate,api,Java,Json,Spring,Hibernate,Api,我有一个表Customers和两列customer\u id和customer\u name。我想用json发送id列表请求,并返回相应的客户名称。但我无法处理dto对象和控制器服务架构 输入dto: public class CustomerSearchDto extends BaseDto { @ApiModelProperty( example = "1", value = "Customer Id", req
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);
}
@api操作(
value=“退货客户”,
响应=Customer.class
)
@后期映射(值=端点.RRESOURCE\u客户\u组\u按\u ID)
公共响应属性GetCustomerById(@RequestBody@Validated CustomerSearchTo CustomerSearchTo){
CustomerDto CustomerDto=新CustomerDto;
List CustomerToList=CustomerService.FindCustomerById(ID);
返回ResponseEntity.ok(CustomerTo);
}
服务类方法:
@Transactional
public List<CustomerDto> findCustomerByIds(List<Long> customerIds) {
List<Customer> customerList = repository.findCustomerById(CustomerIds);
return mapper.mapAsList(CustomerList, CustomerDto.class);
}
@Transactional
公共列表FindCustomerById(列表CustomerId){
List customerList=repository.findCustomerById(customerId);
返回mapper.mapAsList(CustomerList,CustomerDto.class);
}
控制器类中有一些错误。而且我也不确定是否应该为不同的dto类同时定义输入和输出?您不需要定义单独的输入和输出类,相反,您可以根据您的用例构建并返回映射或列表。此外,对于输入,您可以接受包含您要检索的客户ID列表的列表 首先,似乎应该使用
crudepository#findAll(java.lang.Iterable)
通过多个ID搜索实体
另外,在您的特定情况下,创建一个单独的customerSearchTo
作为id
的持有者是多余的-最好只使用long
s操作
因此,只需将
列表id
作为控制器中的参数传递(不要忘记将此参数注释为@RequestBody
或@RequestParam
,具体取决于您希望在url或body中指定这些id的位置),然后从您的服务类调用crudepository#findAll(id)
。将id传递给服务后,我应该从控制器类返回什么?customerDto customerDto=新customerDto;List customerDtoList=customerService.findcustomerIds(id);返回ResponseEntity.ok(CustomerTo);这里我没有使用CustomerToList。但如果我使用return,则会发生错误。如果您成功找到客户-您应该返回CustomerToList,如果您没有要返回的内容-您应该抛出一个异常“没有任何具有此类ID的客户”,或者只返回空列表,具体取决于您的要求Hanks@star67。你能举一个CustomerToList类的例子吗?我应该用什么方法呢?