How to hook up springboot to MongoDB?

时间:2015-05-04 19:33:39

标签: mongodb spring-boot

I'm trying build a rest api using springboot and mongo db. I have a local MongoDB installed and running, and I tried to hook up the springboot to use it. However rest api kept return empty list even though I have tons of data in Mongo. I also tried adding some test data using the rest api, it succeeded but i don't see it in MongoDB. just wondering which mongo it uses? my database is my-store, collection name is processes.

In my application.properties file, I specified the MongoDB database to the one I'm using:

spring.data.mongodb.database=my-store

And here is my java code:

repo:

@RepositoryRestResource(collectionResourceRel = "processes", path="processes")
public interface ProcessRepository extends MongoRepository<Process, String> {
    public List<Process> findAll();
}

controller:

@RestController
@RequestMapping("/processes")
public class ProcessRestController {

    @Autowired
    private ProcessRepository repo;

    @RequestMapping(method=RequestMethod.GET)
    public List<Process> getAll() {
        return repo.findAll();
    }
    ...
    }

Finally figured out what's wrong, the collection name is 'processes' but the java model is 'Process', there are two ways to fix it: 1. rename the java model object to 'Proecesses' 2. keep the java model object 'Process', but added annotation as below:

@Document(collection="processes")  <=== annotation here
public class Process {
    @Id
    private String id;
    private String message;
    private Long highWatermark;

1 个答案:

答案 0 :(得分:0)

我最近遇到了类似的情况。这些收藏品名为&#34; Person&#34 ;,该班级也被命名为#34; Person&#34;。 java程序总是返回一个空列表。有人指出,代码创建的集合,来自java程序的名称以小写字母开头。考虑到这一点,我创建了一个名为&#34; person&#34; (小案例)并且程序返回完整列表。希望这有助于mongoDB中的初学者