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
相关产品推荐
相关产品推荐

