Spring Data JPA aggregate functions on an empty resultset

If you use Spring Data, and if your method returns null when Hibernate can't find a match, make sure you add @org.springframework.lang.Nullable to your method signature:

public interface SomeRepositoryCustom {
    @org.springframework.lang.Nullable
    public Thing findOneThingByAttr(Attribute attr) {
        /* ...your logic here... */
    }
}

This is because Spring Data checks the nullability of your method, and if the annotation is missing, it's going to enforce that you always need to return an object:

/* org.springframework.data.repository.core.support.MethodInvocationValidator */

@Nullable
@Override
public Object invoke(@SuppressWarnings("null") MethodInvocation invocation) throws Throwable {
    /* ...snip... */

    if (result == null && !nullability.isNullableReturn()) {
        throw new EmptyResultDataAccessException("Result must not be null!", 1);
    }

    /* ...snip... */

I used Spring Boot version 2.1.1.RELEASE and Spring Data 2.1.4.RELEASE.


It seems that the EmptyResultDataAccessException exception is thrown when a result from a query was expected to have at least one row (or element) but none was returned.

Related documentation about this can be found here.

I would suggest to run the same query this attempts to run in order to further validate this theory. Now the good question's what to do with this.

You have two options. Either catch the EmptyResultDataAccessException exception at your calling point and handle it directly in there or alternatively you can have an ExceptionHandler which will be tasked with handling such exceptions.

Both ways of handling this, should be OK and you may choose between each depending on your scenario.