springboot2.x基础-整合mongdb

本文是springboot结合SpringBoot starter-data-mongodb 进行增删改查 快速入门教程java

1、准备linux

请参考如下几篇文章git

手把手 linux 下 MongoDB 的安装spring

手把手 linux 下 MongoDB 的使用(一)mongodb

手把手 linux 下 MongoDB 的使用(二)数据库

2、添加依赖springboot

在POM 中添加以下依赖app

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

3、配置文件函数

在配置文件 application.yml 添加以下配置spring-boot

spring:
  data:
    mongodb:
         #单机配置
         host: 192.168.1.1:27017
         #指定操做的数据库
          #authenticationDatabase: admin
         username: admin
         password: 123456
         # 多个IP集群的配置:
         # uri://admin:123456@192.168.252.121:20000,192.168.252.122:20000,192.168.252.12:20000/demo

4、实体类配置

实体映射是经过MongoMappingConverter这个类实现的。它能够经过注释把java类转换为mongodb的文档。

有如下几种注释:

@Id - 文档的惟一标识,在mongodb中为ObjectId,它是惟一的,经过时间戳+机器标识+进程ID+自增计数器(确保同一秒内产生的Id不会冲突)构成。

@Document - 声明此类为mongodb的文档实体类,经过collection参数指定这个类对应的文档名称。@Document(collection=”mongodb”) mongodb对应表

@Indexed - 声明该字段须要索引,建索引能够大大的提升查询效率。

@CompoundIndex - 复合索引的声明,建复合索引能够有效地提升多字段的查询效率。

@Transient - 映射忽略的字段,该字段不会保存到mongodb。

@PersistenceConstructor - 声明构造函数,做用是把从数据库取出的数据实例化为对象。该构造函数传入的值为从DBObject中取出的数据

@Data
@Document(collection = "demo_entity_collection")
public class DemoEntity implements Serializable {

    @Id
    private Long id;
    @Field("title")
    private String title;
    @Field("description")
    private String description;
    @Field("by")
    private String by;
    @Field("url")
    private String url;    
}

5、使用用例

@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class AppTest {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加数据
     */
    @Test
    public void saveDemoTest() {
        DemoEntity demoEntity = new DemoEntity();
        demoEntity.setId(1L);
        demoEntity.setTitle("Spring Boot 中使用 MongoDB");
        demoEntity.setDescription("关注公众号,小罗技术笔记,专一于开发技术的研究与知识分享");
        demoEntity.setBy("xiaoluo");
        demoEntity.setUrl("http://www.yuwowugua.com");
        mongoTemplate.save(demoEntity);
        //  mongoTemplate.insert(demoEntity);
    }

    /**
     * 删除数据
     */
    @Test
    public void removeDemoTest() {
        //经过id 删除
        mongoTemplate.remove(2L);
        //经过其它惟一标识值删除
        Query queryDelete = new Query().addCriteria(Criteria.where("caseCode").is("1314235246"));
        mongoTemplate.remove(queryDelete,DemoMapEntity.class);
    }

    /**
     * 更新数据
     */
    @Test
    public void updateDemoTest() {
        DemoEntity demoEntity = new DemoEntity();
        demoEntity.setId(1L);
        demoEntity.setTitle("Spring Boot 中使用 MongoDB 更新数据");
        demoEntity.setDescription("关注公众号,小罗技术笔记,专一于开发技术的研究与知识分享");
        demoEntity.setBy("xiaoluo");
        demoEntity.setUrl("http://www.yuwowugua.com");

        Query query = new Query(Criteria.where("id").is(demoEntity.getId()));
        Update update = new Update();
        update.set("title", demoEntity.getTitle());
        update.set("description", demoEntity.getDescription());
        update.set("by", demoEntity.getBy());
        update.set("url", demoEntity.getUrl());
        mongoTemplate.updateFirst(query, update, DemoEntity.class);

    }

    /**
     * 查询数据
     */
    @Test
    public void findDemoByIdTest() {
        Query query = new Query(Criteria.where("id").is(1L));
        DemoEntity demoEntity = mongoTemplate.findOne(query, DemoEntity.class);
        System.out.println(JSONObject.toJSONString(demoEntity));
    }


    /**
     * map集合追加数据
     */
    @Test
    public void pushMapDemo() {
        DemoMapEntity demoMapEntity = new DemoMapEntity();
        demoMapEntity.setCaseCode("1314235246");
        Map<String, List<String>> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        map.put("data.valuation", list);
        demoMapEntity.setData(map);
        mongoTemplate.save(demoMapEntity);

        Update update = new Update();
        List<String> list2 = new ArrayList<>();
        list2.add("3");
        list2.add("4");
        update.push("data.valuation", list2);
        Query queryUpdate = new Query().addCriteria(Criteria.where("caseCode").is(demoMapEntity.getCaseCode()));
        mongoTemplate.updateFirst(queryUpdate, update, DemoMapEntity.class);
    }
}

6、源码下载

码云:https://gitee.com/luoluo1995/...

关注公众号-小罗技术笔记

相关文章
相关标签/搜索