gpt4 book ai didi

jpa - JPA 查询的默认返回值

转载 作者:行者123 更新时间:2023-12-01 09:12:29 30 4
gpt4 key购买 nike

我有一个 JPA 查询

@Query(value = "SELECT SUM(total_price) FROM ... WHERE ...", nativeQuery = true)

当有匹配的记录时,它按预期工作。但是当没有匹配的记录时,查询返回 null .

我怎样才能返回零( 0 )而不是 null什么时候找不到记录?

最佳答案

您可以将返回类型更改为 Optional ;

@Query(value = "SELECT SUM(total_price) FROM ... WHERE ...", nativeQuery = true)
Optional<Integer> getSum(...);

或者你可以包装这个 getSum()default方法;
@Query(..)
Integer getSum(...);

default Integer safeGetSum(..) {
return Optional.ofNullable(getSum(..)).orElse(0);
}

更多信息 null handling in repositories

当返回值不是一个列表,或者一些包装器(加上下面的一些其他检查),并且没有匹配的记录时,返回将为空,所以没有巧妙的方法来处理这个 defaultValue=0通过 @Query

The absence of a query result is then indicated by returning null. Repository methods returning collections, collection alternatives, wrappers, and streams are guaranteed never to return null but rather the corresponding empty representation.

关于jpa - JPA 查询的默认返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57002143/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com