美文网首页
mongoDB(4) -- Spring Data中使用

mongoDB(4) -- Spring Data中使用

作者: 卡戎li | 来源:发表于2017-04-01 15:28 被阅读0次
    1. 配置数据源
    spring:
      data:
        mongodb:
          collection: msgDetails
          uri: mongodb://tester01:tester01@127.0.0.1:27016/test
    
    1. pom 添加依赖包
      <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    
    1. 注入工具类
    @Autowired
        private  MongoTemplate mongoTemplate;
    
    1. 增删改查
    Test
        public void saveTest() {
            mongoTemplate.save(person);
        }
    
        @Test
        public void findTest() {
            Person p = mongoTemplate.findOne(query(where("name").is("Joe")), Person.class);
            System.out.println(p);
        }
    
        @Test
        public void updateTest() {
            mongoTemplate.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
            Person p = mongoTemplate.findOne(query(where("name").is("Joe")), Person.class);
            System.out.println(p);
        }
    
        @Test
        public void removeTest() {
            List<Person> people =  mongoTemplate.findAll(Person.class);
            System.out.println(people.size());
    
            Person p = mongoTemplate.findOne(query(where("name").is("Joe")), Person.class);
            mongoTemplate.remove(p);
    
            people =  mongoTemplate.findAll(Person.class);
            System.out.println(people.size());
    
            mongoTemplate.dropCollection(Person.class);
        }
    

    相关文章

      网友评论

          本文标题:mongoDB(4) -- Spring Data中使用

          本文链接:https://www.haomeiwen.com/subject/npviottx.html