例如,以这个jpql查询为例-
@Query("SELECT account.name, account.type From AccountEntity account WHERE account.id=:accountId")
getAccountNameById(@Param(accountId) int accountId); //i know Spring Data Derived Query can handles this automatically - but lets not use this for this discussion.
在上面的jpql查询中,如果没有传递帐户ID,我想为所有帐户ID选择记录。这可能吗?我知道我可以使用另一个查询-getAllAccount()并根据是否存在帐户ID从服务层调用它。但在这种情况下,我必须从repo处理它。
因此,当parm值丢失或为空时,JPQL可能返回所有记录。
有点晚了但是…
在这个例子中,第一个WHEN将评估: CountId,如果它为null,则查询将返回所有元素,在第二个WHEN中,如果:CountId不为null,则将返回所有元素,其中account.id=:CountId
SELECT account.name, account.type FROM AccountEntity account
WHERE CASE WHEN :accountId IS NULL THEN TRUE
WHEN :accountId IS NOT NULL AND account.id = :accountId THEN TRUE ELSE FALSE END
测试参数是否为空
SELECT account.name, account.type From AccountEntity account WHERE (:accountId is null or account.id=:accountId)