zoukankan      html  css  js  c++  java
  • MongoDB-- SpringBoot

    SpringData中对mongoDB提供了支持,除了template方法外,还支持jpa格式的Repository.

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
            </dependency>
    
    #授权数据库需要填写
    spring.data.mongodb.authentication-database=admin
    #参数不填就是默认值
    spring.data.mongodb.host=xxxxx
    spring.data.mongodb.database=local
    spring.data.mongodb.username=xx
    spring.data.mongodb.password=xx
    

    实体类

    这个实体类相当于mongo中的集合,类名就是集合名,每个对象相当于文档。

    这里的id会取代mongo中的_id字段。

    public class Person {
        private Integer id;
        private String name;
        private String sex;
        private int age;
        //其他略去
    }
    

    MongoTemplate

    MongoTemplate模板方法,curd都支持,同时Query支持复杂查询。

      @Autowired
      MongoTemplate mongoTemplate;	
    
    	@Test
        void contextLoads() {
            Person person = new Person(102, "小黄人", "男", 18);
            Person insert = mongoTemplate.insert(person);
            System.out.println(insert);
        }
    
        @Test
        public void test2(){
            Person person = mongoTemplate.findById(102, Person.class);
            System.out.println(person);
        }
    
        @Test
        public void test3(){
            Query query = new Query();
            query.limit(1);//分页
            List<Person> people = mongoTemplate.find(query, Person.class);
            people.forEach(k->{
                System.out.println(k);
            });
    
        }
    

    MongoRepository

    MongoRepository类似Jpa的操作,继承父类即可。

    public interface PersonDao extends MongoRepository<Person, Integer> {
    
    }
    @EnableMongoRepositories注解也是需要的
    实体类也可以通过@Document等注解修饰
    
    
    @Autowired
        PersonDao personDao;
    
        @Test
        public void test4(){
            List<Person> all = personDao.findAll();
            all.forEach(System.out::println);
        }
    
        @Test
        public void test5(){
            personDao.save(new Person(103, "Sally", "女", 14));
        }
    
  • 相关阅读:
    用Visual C#创建Windows服务程序(转)
    输入字符串的格式不正确(异常详细信息: System.FormatException: 输入字符串的格式不正确。)
    pv操作二
    双进程struct sigaction中mask阻塞信号
    pv操作一
    sigprocmask
    共享内存二
    面向接口编程
    类之间的几种关系
    sigaction函数一
  • 原文地址:https://www.cnblogs.com/cgl-dong/p/13820948.html
Copyright © 2011-2022 走看看