33

I have an @Entity Video having a one-to-many relation with a List<Tag> tags as one of its fields. I use the following @Repository using Spring Data to get the most popular tags:

@Repository
public interface TagRepository extends CrudRepository<Tag, Integer>{
    @Query("SELECT t FROM Tag t WHERE (SELECT SUM(v.views) FROM Video v WHERE t MEMBER OF v.tags) > 0")
    public List<Tag> findMostViewedTags(int maxTags);
}

The Query is processed and considered valid by Spring, I tested the generated SQL vs my database locally and it returned 2 Tags. In my Code however, I receive the value Null when I call the method findMostViewedTags(100).

The Query lookup strategy is the default "CREATE_IF_NOT_FOUND".

  1. If there are no results found, should the method return an empty list or Null? My desired behavior is to receive an empty list.
  2. Why does the method call return Null instead of a List<Tag> with size() 2?
1
  • maxTags isn't used or that isn't the query you are actually executing. Commented Jun 9, 2016 at 14:18

2 Answers 2

48
  1. The normal behavior is indeed returning an empty list if no results are found. If a List<Object> is the return value of the method in the defined interface, the method should never return Null.
  2. The problem is that a parameter is given to the method and is not used anywhere in the Query. For some reason Spring decides to return a Null in that case. Solution: remove the unused parameter or use the parameter in the Query.
Sign up to request clarification or add additional context in comments.

4 Comments

The "Solution" should include raise a bug on Spring to better cater for that situation
@Vjeetje is it specified anywhere in the docs that it returns an empty list if no results are found? I cant find it
@osmingo Here you go.. docs.spring.io/spring-data/jpa/docs/current/reference/html/… Repository methods returning collections, collection alternatives, wrappers, and streams are guaranteed never to return null but rather the corresponding empty representation
The new, and updated link, whether null can be returned: docs.spring.io/spring-data/jpa/reference/repositories/…
7

I have experienced similar problem. The cause was that I was using Mockito and have not correctly mocked the data with when().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.