数据库
首页 > 数据库> > Spring Boot:整合MongoDB

Spring Boot:整合MongoDB

作者:互联网

Spring Data MongoDB

相关依赖:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

配置文件application.yml

spring:
  data:
    mongodb:
      host: 192.168.1.43
      port: 27017
      username: root
      password: root
      authentication-database: admin
      database: test 

启动springboot项目:

image-20210112191405835

注解描述实体类型

Id注解,是springdata提供的一个公共注解,用来描述实体类型中的主键属性.

在springdata-mongodb环境中,如果实体类型的属性命名为id或_id时,且这个属性就是主键属性时,可以省略Id注解.

只有主键类型为String或ObjectId类型时,MongoDB才能自动生成,其他类型的主键必须手工赋值。

@Document("user")//对应哪一个集合
@Data@EqualsAndHashCode
public class User implements Serializable {

    @Id
    private Long id;
    /**
     * field注解,用来描述类型的属性和集合中的字段的映射关系
     */
    @Field("name")
    private String username;
    private String password;
    private String email;
    private List<String> courses;
}

新增数据

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    void contextLoads() {
        User user = new User();
        user.setId(100L);
        user.setUsername("wj");
        user.setPassword("wj");
        user.setEmail("123@qq.com");
        user.setCourses(Arrays.asList("spring","dubbo"));
        mongoTemplate.insert(user);
    }

image-20210112191721901

当我们的实体类什么springdata注解都没有加上时,也是可以插入成功的:

@Data
@EqualsAndHashCode
public class Item {
    private String code;
    private Integer num;
    private Double price;
}

    @Test
    public void testInsert(){
        Item item = new Item();
        item.setCode("123");
        item.setNum(11);
        item.setPrice(22.5);
        mongoTemplate.insert(item);
    }

image-20210112192200830

保存数据save

save方法:如果存在该条数据则直接覆盖原数据(判断主键是否相同),不存在则新增。

    public void testSave(){
        User user = new User();
        user.setUsername("aaa");
        user.setId(101L);
        user.setCourses(Arrays.asList("spring","dubbo"));
        mongoTemplate.save(user);

        User user2 = new User();
        user2.setUsername("wj2");
        user2.setId(100L);
        mongoTemplate.save(user2);
    }

image-20210112192900436

更新数据

更新单一数据

updateFirst方法的三个参数:

    @Test
    public void testUpdate(){
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("wj2"));
        Update update = new Update();
        update.set("name","wj3");
        update.set("email","9999@qq.com");
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, User.class);
        System.out.println(updateResult.getMatchedCount());//匹配行数
        System.out.println(updateResult.getModifiedCount());//修改行数
    }

image-20210112193901696

更新多数据

    @Test
    public void testUpdateMulti(){
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").lte(200));
        Update update = Update.update("password","123456");
        mongoTemplate.updateMulti(query,update,User.class);
    }

image-20210112194357234

更新或新增

更新,如果更新数据不存在,则新增

    @Test
    public void testUpset(){
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("zhangsan"));
        Update update = Update.update("password", "123");
        mongoTemplate.upsert(query,update,User.class);
    }

image-20210112194716889

发现使用upset插入的数据,类的类型丢失,所以不建议使用upset。

删除

根据条件删除

    @Test
    public void testDelete(){
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("zhangsan"));
        mongoTemplate.remove(query,User.class);
    }

image-20210112195125876

根据主键删除

根据java对象删除数据,Spring Data MongoDB找到这个对象对应的集合,使用主键作为条件删除。

    @Test
    public void testDeleteByObj(){
        User user = new User();
        user.setId(100L);
        user.setUsername("哈哈哈");
        mongoTemplate.remove(user);
    }

image-20210112195432996

查询数据

查询全部数据

    @Test
    public void testFind(){
        List<User> users = mongoTemplate.findAll(User.class);
        users.forEach(System.out::println);
    }

image-20210112195913918

单数据查询

有两种:findOne和findById

    @Test
    public void findOne(){
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("wj3"));
        User one = mongoTemplate.findOne(query, User.class);
        System.out.println(one);

        User user = mongoTemplate.findById(101L, User.class);
        System.out.println(user);
    }

image-20210112200601357

条件查询

    @Test
    public void testQuery(){

        Query query = new Query();
        query.addCriteria(
        //范围查询
                Criteria.where("_id").lt(103L).gte(100L)
        );

        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }

image-20210112201021693

正则查询:不需要写正则的起始和结束标记

    @Test
    public void testQuery(){
        Query query = new Query();
        query.addCriteria(
                Criteria.where("name").regex("wj")
        );
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }

复合多条件查询

查询密码中包含5且主键小于103的User

    @Test
    public void find(){
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("password").regex("5"),Criteria.where("_id").lt(103L));
        query.addCriteria(criteria);
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }

image-20210112201710533

查询密码中包含5或主键小于103的User

    @Test
    public void find(){
        Query query = new Query();
        Criteria criteria = new Criteria();    criteria.orOperator(Criteria.where("password").regex("5"),Criteria.where("_id").lt(103L));
        query.addCriteria(criteria);
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }

image-20210112201802370

排序

    @Test
    public void order(){
        Query query = new Query();
        //主键降序排列
        query.with(Sort.by(Sort.Direction.DESC,"_id"));
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }

分页

页码从0开始

    @Test
    public void page(){
        Query query = new Query();
        query.with(PageRequest.of(1,2));
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }

排序再分页

    @Test
    public void page(){
        Query query = new Query();
        query.with(PageRequest.of(1,2,Sort.by(Sort.Direction.DESC,"_id")));
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }

聚合

    @Test
    public void agg(){
        GroupOperation count = Aggregation.group().count().as("count");
        TypedAggregation<User> aggregation = TypedAggregation.newAggregation(User.class, count);
        AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, Map.class);
        Map map = result.getUniqueMappedResult();
        System.out.println(map);
    }

标签:Spring,Boot,new,MongoDB,mongoTemplate,User,Query,query,public
来源: https://www.cnblogs.com/wwjj4811/p/14269132.html