Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 438
Sergii Avatar asked Jun 23 '17 14:06

Sergii


People also ask

What does JPA repository return if not found?

From my little and personal experience, if you search for an object on your repo, for example by Id or Name the named query method returns an object of type T , but if no results are found from your repo, it will return null.

How do I limit query results in Spring Data JPA?

Limiting query results in JPA is slightly different to SQL; we don't include the limit keyword directly into our JPQL. Instead, we just make a single method call to Query#maxResults, or include the keyword first or top in our Spring Data JPA method name. As always, the code is available over on GitHub.

What does findById return in JPA?

Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.

What is the limit clause alternative in JPQL?

You are using JPQL which doesn't support limiting results like this. When using native JPQL you should use setMaxResults to limit the results. However you are using Spring Data JPA which basically makes it pretty easy to do. See here in the reference guide on how to limit results based on a query.


1 Answers

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.

like image 105
YCF_L Avatar answered Sep 20 '22 22:09

YCF_L