为什么用mongoDb findAll()进行Spring-boot返回空数组?

时间:2019-07-13 19:43:00

标签: mongodb spring-boot

我有一个Spring Boot应用程序连接到本地mongoDB数据库。当我尝试从集合中获取所有记录时,它返回一个空数组。在输出中显示连接到端口27017。在运行应用程序时它不会给我任何错误,而当我键入{{3}时仅返回一个空数组} 我在这里想念什么?

模型类

$PROFILE

控制器类

package SpringBoot.Training.Management.Tool.SpringBootTMTCourses.Model;

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;

public class Courses {
    @Id
    public ObjectId _id;

    public String courseID;
    public String courseName;

    public Courses(ObjectId _id, String courseID, String courseName) {
        super();
        this._id = _id;
        this.courseID = courseID;
        this.courseName = courseName;
    }

    public String get_id() {
        return _id.toHexString();
    }

    public void set_id(ObjectId _id) {
        this._id = _id;
    }

    public String getCourseID() {
        return courseID;
    }

    public void setCourseID(String courseID) {
        this.courseID = courseID;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

}

存储库类

package SpringBoot.Training.Management.Tool.SpringBootTMTCourses.Controller;

import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import SpringBoot.Training.Management.Tool.SpringBootTMTCourses.Model.Courses;
import SpringBoot.Training.Management.Tool.SpringBootTMTCourses.Repository.CoursesRepository;

@RestController
@RequestMapping("/courses")
public class CourseController {
    @Autowired
    private CoursesRepository repository;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<Courses> getAllCourses() {
      return repository.findAll();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Courses getPetById(@PathVariable("id") ObjectId id) {
      return repository.findBy_id(id);
    }
}

MongoDb输出

package SpringBoot.Training.Management.Tool.SpringBootTMTCourses.Repository;

import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;

import SpringBoot.Training.Management.Tool.SpringBootTMTCourses.Model.Courses;

public interface CoursesRepository extends MongoRepository<Courses, String> {
    Courses findBy_id(ObjectId _id);
}

1 个答案:

答案 0 :(得分:0)

出现此问题是因为在模型类中未明确指定集合名称,因此spring-data将类名称(Courses)的集合名称导出为驼峰大小写(courses)。由于您的实际收藏夹称为Courses,所以没有找到结果。

您必须:

  1. 将集合重命名为courses OR
  2. 用正确的集合名称注释模型类,如下所示:

    @Document(collection = "Courses")

    public class Courses {