3 回答
TA贡献1772条经验 获得超5个赞
不知道如何,但下面的代码对我有用
@Query("select a from MLFM_ORDER_OWNER a where a.businessTypeId.typeId=COALESCE(:typeId,a.businessTypeId.typeId) and a.ownerCountry.countryId=COALESCE(:countryId,a.ownerCountry.countryId) and a.ownerName LIKE %:name and a.shortCode LIKE %:code")
public List <ModelOrderOwner> findOwnerDetails(@Param("typeId")Long typeId,@Param("countryId")Long countryId,@Param("name")String name,@Param("code")String code);
并在控制器中
@RequestMapping(path="/owners/search")
public String getAllOwner(Model model,@RequestParam("owner_name") String name,@RequestParam("shortCode") String code,
@RequestParam("phoneNumber") String phoneNumber,@RequestParam("countryName") Long countryId,
@RequestParam(value = "active", required = false) String active, @RequestParam("businessType") Long typeId
) {
if(typeId==0)
typeId=null;
if(countryId==0)
countryId=null;
model.addAttribute("ownerList",ownerRepository.findOwnerDetails(typeId, countryId, name, code, status));
return "data_list";
}
TA贡献2003条经验 获得超2个赞
JPQL 不支持可选参数。在 JPQL 中没有简单的方法可以做到这一点。您将不得不使用OR运算符编写多个WHERE子句。
PS:您可能希望针对您的用例查看Query by Example。它支持处理空参数。
TA贡献1811条经验 获得超6个赞
现在回答为时已晚,但对于任何寻找解决方案的人来说,还有一种更简单的方法如下:
在我的情况下,我的控制器是这样的:
@RestController
@RequestMapping("/order")
public class OrderController {
private final IOrderService service;
public OrderController(IOrderService service) {
this.service = service;
}
@RequestMapping(value = "/{username}/", method = RequestMethod.GET)
public ResponseEntity<ListResponse<UserOrdersResponse>> getUserOrders(
@RequestHeader Map<String, String> requestHeaders,
@RequestParam(required=false) Long id,
@RequestParam(required=false) Long flags,
@RequestParam(required=true) Long offset,
@RequestParam(required=true) Long length) {
// Return successful response
return new ResponseEntity<>(service.getUserOrders(requestDTO), HttpStatus.OK);
}
}
正如你所看到的,我有Username作为@PathVariable和length和offset这是我所需要的参数,但我接受id并flags用于过滤的搜索结果,所以他们都是我的可选参数,并没有必要调用REST服务。
现在在我的存储库层中,我刚刚创建了@Query如下:
@Query("select new com.ada.bourse.wealth.services.models.response.UserOrdersResponse(FIELDS ARE DELETED TO BECOME MORE READABLE)" +
" from User u join Orders o on u.id = o.user.id where u.userName = :username" +
" and (:orderId is null or o.id = :orderId) and (:flag is null or o.flags = :flag)")
Page<UserOrdersResponse> findUsersOrders(String username, Long orderId, Long flag, Pageable page);
就是这样,你可以看到,我检查了我的可选参数与(:orderId is null or o.id = :orderId)和(:flag is null or o.flags = :flag),我认为它需要强调的是,我检查了我的说法与is null条件不是我的列中的数据,因此,如果客户端发送Id和flags对我的参数,我会筛选与他们的结果否则我只是查询username哪个是我的@PathVariable.
添加回答
举报