Java 弹簧数据 jpa。如果没有结果返回默认值,则查找最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44723744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring data jpa. Find max if no result return default value
提问by Sergii
I've implemented in my spring repository interface:
我已经在我的 spring 存储库界面中实现了:
@Query("SELECT max(ch.id) FROM MyEntity ch")
Long getMaxId();
It works correctly if db is not empty. If I start my environment with test configuration (H2DB is used) - there is no data in the very beginning. And result returned by getMaxId()
is null. I would like to have here 0.
如果 db 不为空,它可以正常工作。如果我使用测试配置启动我的环境(使用 H2DB) - 一开始没有数据。返回的结果getMaxId()
为null。我想在这里0。
Is it possible to modify my *JpaRepository
to have 0result? If yes, how it should be modified?
是否可以修改我的结果*JpaRepository
为0?如果是,应该如何修改?
采纳答案by YCF_L
You can use coalesce
like :
你可以使用coalesce
像:
@Query("SELECT coalesce(max(ch.id), 0) FROM MyEntity ch")
Long getMaxId();
If there are no data it will return 0 instead of null.
如果没有数据,它将返回 0 而不是 null。