SpringBoot连接MongoDB

  • 因为使用了MongoTemplate,我只能用Spring的依赖包去连接
  • SpringBoot的集成包spring-boot-starter-data-mongodb不支持这种写法,还需要研究
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>2.0.9.RELEASE</version>
        </dependency>

application.properties

spring.data.mongodb.host=172.17.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=test
spring.data.mongodb.database=test
spring.data.mongodb.username=root
spring.data.mongodb.password=123456

基本操作

  • 注入MongoTemplate
    @Autowired
    protected MongoTemplate mgt;
  • 保存
    public void save(T entity) {
        mgt.save(entity);
    }
  • 更新
    public void update(T entity) {

        // 反向解析对象
        Map<String, Object> map = null;
        try {
            map = parseEntity(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // ID字段
        String idName = null;
        Object idValue = null;

        // 生成参数
        Update update = new Update();
        if (EmptyUtil.isNotEmpty(map)) {
            for (String key : map.keySet()) {
                if (key.indexOf("{") != -1) {
                    // 设置ID
                    idName = key.substring(key.indexOf("{") + 1, key.indexOf("}"));
                    idValue = map.get(key);
                } else {
                    update.set(key, map.get(key));
                }
            }
        }
        mgt.updateFirst(new Query().addCriteria(where(idName).is(idValue)), update, getEntityClass());
    }
  • 删除
    public void delete(Serializable... ids) {
        if (EmptyUtil.isNotEmpty(ids)) {
            for (Serializable id : ids) {
                mgt.remove(mgt.findById(id, getEntityClass()));
            }
        }
    }
  • 查找
    public T find(Serializable id) {
        return mgt.findById(id, getEntityClass());
    }

https://www.cnblogs.com/lemonbar/p/3893458.html
https://blog.csdn.net/qq_16313365/article/details/70142729
https://www.cnblogs.com/xiaoqi/p/queries-in-spring-data-mongodb.html
https://stackoverflow.com/questions/28958789/connecting-to-mongodb-3-0-with-java-spring

    原文作者:TJJ
    原文地址: https://www.jianshu.com/p/d9337ccb063e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞