hibernate 如何在HQl中传递'null'字符串后获取空记录

nfzehxib  于 2022-11-30  发布在  其他
关注(0)|答案(2)|浏览(192)

我正在尝试编写一个查询。
下面是到目前为止的查询。

@Query(value = "select cn from CapNumber cn " +
"WHERE (:#{#request.number} = '' OR cn.number LIKE CONCAT('%',:#{#request.number},'%')) " +
"AND (:#{#request.name} IS '' OR cn.name LIKE CONCAT('%',:#{#request.name},'%') )" +
"AND (:#{#request.smsStatus} IS '' OR cn.smsStatus = :#{#request.smsStatus} )" +
"AND (:#{#request.internalId} IS '' OR cn.internalId LIKE CONCAT('%',:#{#request.internalId},'%') )")
Page<CapNumber> search(NumbersRequest request, Pageable pageable);

如果smsStatus为“”,则根据当前查询为否。如果传递的关键字正确,则将获取所有记录和数据。
现在我想要所有的记录中的smsStatus是空的,不知道我怎么做。我知道我必须使用的情况下是空的,但不知何故,我尝试了什么是不工作。
谁能帮帮忙

k5hmc34c

k5hmc34c1#

您可以使用IS NULL检查对参数未设置值的逻辑分支执行no-op操作。

@Query(value = "select cn from CapNumber cn " +
    "WHERE (:#{#request.number} IS NULL OR cn.number LIKE CONCAT('%',:#{#request.number},'%')) " +
    "AND (:#{#request.name} IS NULL OR cn.name LIKE CONCAT('%',:#{#request.name},'%') )" +
    "AND (:#{#request.smsStatus} IS NULL OR cn.smsStatus = :#{#request.smsStatus} )" +
    "AND (:#{#request.internalId} IS NULL OR cn.internalId LIKE CONCAT('%',:#{#request.internalId},'%') )")
Page<CapNumber> search(NumbersRequest request, Pageable pageable);
euoag5mw

euoag5mw2#

您可以添加COALESCE(cn.smsStatus,'NULL') = :#{#request.smsStatus}
如果request.smsstatus为“NULL”(字符串),则在cn.smsstatus为NULL时条件将变为真,因为COALESCE将采用第一个NOT NULL值。

@Query(value = "select cn from CapNumber cn " +
"WHERE (:#{#request.number} = '' OR cn.number LIKE CONCAT('%',:#{#request.number},'%')) " +
"AND (:#{#request.name} IS '' OR cn.name LIKE CONCAT('%',:#{#request.name},'%') )" +
"AND (:#{#request.smsStatus} IS '' OR COALESCE(cn.smsStatus,'NULL') = :#{#request.smsStatus}  OR cn.smsStatus = :#{#request.smsStatus} )" +
"AND (:#{#request.internalId} IS '' OR cn.internalId LIKE CONCAT('%',:#{#request.internalId},'%') )")
Page<CapNumber> search(NumbersRequest request, Pageable pageable);

相关问题