Spring Data JPA - 通过嵌套对象属性查找对象

时间:2018-02-18 20:23:01

标签: java spring jpa spring-data spring-data-jpa

我已经基于此article实现了灵活的搜索REST API。

除了片刻之外,该API工作得很好。当我想通过一些嵌套属性找到一个对象时,JPA找不到任何东西。

例如,有一个像这样的Order模型(cutted version):

@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "date")
private Date date;

@NotNull
@Column(name = "description")
private String description;

@NotNull
@Column(name = "delivery_price")
private Double price;

@NotNull
@Column(name = "status")
private String status;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
private User user;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "courier_id")
private User courier;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "address_from_id")
private Address addressFrom;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "address_to_id")
private Address addressTo;

控制器请求:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?> getOrders(@RequestParam(value = "search", required = false) String search,
                                   Pageable pageable) {
    OrderSpecificationsBuilder builder = new OrderSpecificationsBuilder();
    Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
    Matcher matcher = pattern.matcher(search + ",");
    while (matcher.find()) {
        builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
    }

    Specification<Order> spec = builder.build();

    Page<Order> orders = orderService.findAll(spec, pageable);
    Page<OrderDto> ordersDtos = orders.map(OrderDto::toDto);
    return new ResponseEntity<>(ordersDtos, HttpStatus.OK);
}

规范类在这里on Github.

整个代码可在此处on Github.

获取

所以我想找到快递id 10的订单,例如。

我使用 /api/v1/orders?search=courier.id:10 等请求,但未找到任何结果。

据我所知,SearchCriteria是在一种通用API中实现的,我不知道它为什么只适用于search = price:10之类的简单查询等等。

0 个答案:

没有答案