繁体   English   中英

在spring jpa查询中检索可选字段的结果

[英]retrieve result for an optional field in spring jpa query

我是Spring和Java的新手,我有一种情况,在这里我喜欢如下查询:

当我有一个po.id值时,我可以这样搜索:

表格服务:

prescriptionOrderRepository.searchPharmacyOrders(args);

我正在这样写我的春季查询:

@Query(value = "select po from PrescriptionOrder po WHERE po.pharmacyId = :pharmacyId  "
            + "AND po.id = :idValue  AND po.active = :active ORDER BY po.createdAt DESC")
    Page<PrescriptionOrder> searchPharmacyOrders(@Param("pharmacyId") Long pharmacyId,
            @Param("idValue") Long idValue, Pageable pageRequest, @Param("active") Boolean active);

假设如果我必须要求,po.id是一个可选字段,意味着如何编写查询。

我一直期望参数,它们默认为null,或者我得到一个值且必须匹配。 因此,对于参数:idValue,您的查询具有

... AND (po.id = :idValue OR :idValue is null) ...

例如,当您来自一个使用GET变量的Controller类时,您始终可以将它们用作默认null,或者获取值且必须匹配。

在您的示例中,该查询总计...

WHERE (po.pharmacyId = :pharmacyId AND po.id = :idValue AND po.active = :active

更改为:

WHERE ((po.pharmacyId = :pharmacyId OR :pharmacyId is null) AND (po.id = :idValue OR :idValue is null) AND (po.active = :active OR :active is null)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM