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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With