spring data jpa中条件查询中包含in(param0,param1,param2)
@Override
public Page<PaymentOrder> findPaymentOrder(String agent, Long userId, OrderType orderType, TradeStatus tradeStatus, Pageable pageable) throws ServiceException {
return paymentOrderRepository.findAll(where(agent, userId, orderType, tradeStatus), pageable);
}
private Specification<PaymentOrder> where(final String agent, final Long userId, OrderType orderType, TradeStatus tradeStatus) {
return (root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<Predicate>();
if (userId != null) {
predicates.add(criteriaBuilder.equal(root.<Long>get("userId"), userId));
}
if (orderType != null) {
predicates.add(criteriaBuilder.equal(root.<Enum<OrderType>>get("orderType"), orderType));
}
if (tradeStatus != null) {
predicates.add(criteriaBuilder.equal(root.<Enum<TradeStatus>>get("tradeStatus"), tradeStatus));
}
if (StringUtils.isNotEmpty(agent)) {
/* 1、设置请求服务名 */
URI uri = util.getServiceUrl("user", "error url request!");
String url = uri + "/v1.0/user/Platform/getUserIdByPlatform";
/* 2、设置请求参数 */
MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<>();
requestEntity.add("agent", agent);
/* 3、创建连接 */
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(url, requestEntity, String.class);
/* 4、处理返回结果 */
JSONObject jsonObject = JSONObject.fromObject(result);
String resp_code = jsonObject.getString("resp_code");
if (!CommonConstants.SUCCESS.equals(resp_code)) {
throw new ServiceException("获取userId失败,请稍后再试!");
}
result = jsonObject.getString("result");
jsonObject = JSONObject.fromObject(result);
String userId1 = jsonObject.getString("userId");
/* 5、连接sql语句:in(param0,param1,param2...) */
if (StringUtils.isNotEmpty(userId1)) {
CriteriaBuilder.In<Long> inUserId = criteriaBuilder.in(root.<Long>get("userId"));
String[] split = userId1.split(",");
for (int i = 0; i < split.length; i++) {
inUserId.value(Long.valueOf(split[i]));
}
predicates.add(inUserId);
}
}
return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
};
}
复制代码
条件查询结果:
select count(paymentord0_.order_id) as col_0_0_ from t_payment_order paymentord0_ where paymentord0_.order_type=? and paymentord0_.trade_status=? and (paymentord0_.user_id in (493888485 , 882204580 , 665194426))
复制代码