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));
    }
posted @ 2020-10-15 15:41  cgl_dong  阅读(122)  评论(0编辑  收藏  举报