Spring data jpa. Find max if no result return default value
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? 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:/