You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoRepository findAll()返回空列表问题排查及解决

问题:Spring Data MongoDB的findAll()返回空列表但数据库存在数据

相关代码

MovieService.java

package com.example.movies;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MovieService
{
    @Autowired
    private MovieRepository movieRepository;

    public List<Movie> allMovies()
    {
        return movieRepository.findAll();
    }
}

MovieController.java

package com.example.movies;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/v1/movies")
public class MovieController
{
    @Autowired
    private MovieService movieService;

    @GetMapping
    public ResponseEntity<List<Movie>> getAllMovies()
    {
        return new ResponseEntity<List<Movie>>(movieService.allMovies(), HttpStatus.OK);
    }
}

问题现象

按照视频指导完成上述代码修改后,allMovies()方法中调用的findAll()未按预期工作:返回空列表而非数据库中已存在的Movie对象列表。已确认MongoDB内存在对应数据,且程序与数据库之间无连接错误。

问题根源与解决(编辑补充)

问题出在集合名称不匹配:Spring Data MongoDB默认会将实体类名(Movie)转为复数形式作为集合名称(movies),但实际数据库中使用的集合名称是movie。修改集合名称为movie(或通过@Document(collection = "movie")注解指定实体对应的集合名)后,功能恢复正常。

内容的提问来源于stack exchange,提问作者Trần Khôi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 15:17:35