SpringBooot整合mongoDB

1、导入jar包依赖

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-mongodb</artifactId>

</dependency>

   

2、配置文件

这里配置的是无身份验证

mongodb://ip:port

#yml配置

data:

  mongodb:

    uri: mongodb://10.20.37.211:27017,10.20.37.212:27017,10.20.37.213:27017

    database: signa

   

这里是有身份验证

mongodb://username:password//ip:port

#properties配置。

spring.data.mongodb.uri=mongodb://mongo:mongo@192.168.2.128:27017

spring.data.mongodb.database=test_mongo

   

3、示例代码

   

@Getter

@Setter

@ToString

public class Student {      

    private String id ;    

    private String name ;    

    private String clazz ;

}

   

   

@Service

public class TestMongoService {

      

    private MongoTemplate mongoTemplate ;    

    public TestMongoService(MongoTemplate mongoTemplate) {

        this.mongoTemplate = mongoTemplate;    

    }  

 

    public String findAll(){        

        List<Students> list = mongoTemplate.findAll(Student.class,"student");

        for (Students st : list){

            System.out.println(st);        

        }              

        return list.toString() ; 

}   

}

   

posted @ 2020-11-11 11:26  黑质白章  阅读(161)  评论(0编辑  收藏  举报