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

Sergii picture Sergii · Jun 23, 2017 · Viewed 25.9k times · Source

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?

Answer

YCF_L picture YCF_L · Jun 23, 2017

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.