Vjeetje
Vjeetje

Reputation: 5404

Spring JPA Query returns Null instead of List

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?

Upvotes: 33

Views: 86560

Answers (2)

user1747134
user1747134

Reputation: 2482

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

Upvotes: 7

Vjeetje
Vjeetje

Reputation: 5404

  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.

Upvotes: 48

Related Questions