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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:42:13  来源:igfitidea点击:

Spring data jpa. Find max if no result return default value

javaspringspring-data-jpahql

提问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 *JpaRepositoryto have 0result? If yes, how it should be modified?

是否可以修改我的结果*JpaRepository0?如果是,应该如何修改?

采纳答案by YCF_L

You can use coalescelike :

你可以使用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。