Spring JPA Query returns Null instead of list

I have a @Entity Videoone-to-many relationship with a List<Tag> tagsas one of its fields. I use the following @Repositoryusing 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 request is processed and considered valid using Spring, I tested the generated SQL version and my database locally, and it returned 2 tags. However, in my code, I get Null when I call the findMostViewedTags (100) method.

The default query search strategy is "CREATE_IF_NOT_FOUND".

  • If no results are found, should the method return an empty list or Null? My desire is to get an empty list.
  • Why does the method call return Nullinstead of List<Tag>with size () 2?
+4
source share
2 answers
  • Normal behavior does return an empty list if no results are found. If a List<Object>is the return value of a method in a specific interface, the method should never return Null.
  • The problem is that the parameter is assigned to the method and is not used anywhere in the request. For some reason, Spring decides to return zero in this case. Solution: delete the unused parameter or use the parameter in the query.
+4
source

I had a similar problem. The fact is, I used Mockito and incorrectly mocked data with when().

+2

Source: https://habr.com/ru/post/1626242/


All Articles