Java Spring JPA 查询返回 Null 而不是 List

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35045661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:15:57  来源:igfitidea点击:

Spring JPA Query returns Null instead of List

javaspringjpaspring-dataspring-data-jpa

提问by Vjeetje

I have an @Entity Videohaving a one-to-manyrelation with a List<Tag> tagsas one of its fields. I use the following @Repositoryusing Spring Datato get the most popular tags:

我与 a作为其字段之一@Entity Video具有一对多关系List<Tag> tags。我使用以下@Repository使用Spring Data来获取最受欢迎的标签:

@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 Queryis processed and considered valid by Spring, I tested the generated SQLvs my database locally and it returned 2 Tags. In my Code however, I receive the value Nullwhen I call the method findMostViewedTags(100).

查询处理和认为是有效的春天,我测试生成的SQLVS我的数据库在本地,它返回2个标签。然而,在我的代码中,当我调用 findMostViewedTags(100) 方法时,我收到了Null值。

The Query lookup strategy is the default "CREATE_IF_NOT_FOUND".

查询查找策略是默认的“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 Nullinstead of a List<Tag>with size() 2?
  1. 如果没有找到结果,该方法应该返回一个空列表还是Null?我想要的行为是接收一个空列表。
  2. 为什么方法调用返回Null而不是List<Tag>with size() 2?

采纳答案by Vjeetje

  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 Springdecides to return a Nullin that case. Solution: remove the unused parameter or use the parameter in the Query.
  1. 如果没有找到结果,正常行为确实返回一个空列表。如果 aList<Object>是已定义接口中方法的返回值,则该方法不应返回Null
  2. 问题是该方法有一个参数,并没有在Query 中的任何地方使用。出于某种原因,Spring决定在这种情况下返回Null。解决方案:删除未使用的参数或使用Query 中的参数。

回答by user1747134

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

我遇到过类似的问题。原因是我使用的是 Mockito 并且没有正确地使用 .mockito 模拟数据when()