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

天涯浪子 提交于 2019-12-03 17:13:17

问题


I've implemented in my spring repository interface:

@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.


Is it possible to modify my *JpaRepository to have 0 result? If yes, how it should be modified?


回答1:


You can use coalesce like :

@Query("SELECT coalesce(max(ch.id), 0) FROM MyEntity ch")
Long getMaxId();

If there are no data it will return 0 instead of null.



来源:https://stackoverflow.com/questions/44723744/spring-data-jpa-find-max-if-no-result-return-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!