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

Sergii :

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?

YCF_L :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=431448&siteId=1