springboot2 整合mongodb

在springboot2中使用MongoDB

1、引入依赖

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

2、写入yml文件

spring:
  data:
    mongodb:
      uri: mongodb://user:pwd@localhost:27017/database

注意,下划线部分,根据本机设置,自己调整,如果没有设置权限,去掉黄色部分即可。

还有需要注意的是,涉及到权限时,要不就是使用uri的方式指定路径,要不就使用port、host、username等指定,不可混用。

3、上代码(我觉着定义成静态方法更合适,先不调整了,这个可以用)

@Service
public class MongoUtils {

    @Autowired
    private MongoTemplate mongoTemplate;

    public void insertOne(String collection, Document document) {
        mongoTemplate.getCollection(collection).insertOne(document);
    }

    public void insertMany(String collection, List<Document> documentList) {
        mongoTemplate.getCollection(collection).insertMany(documentList);
    }

    public Document findById(String collection, String id) {
        Document query = new Document();
        query.put("_id", id);
        return findOne(collection, query);
    }

    public Document findOne(String collection, Bson filter) {
        return findMany(collection, filter).get(0);
    }

    public List<Document> findAll(String collection) {
        return findMany(collection, null);
    }

    public List<Document> findMany(String collection, Bson filter) {
        filter = handelId(filter);
        MongoCollection<Document> mongoCollection = mongoTemplate.getCollection(collection);
        FindIterable<Document> findIterable = mongoCollection.find();
        MongoCursor<Document> mongoCursor = findIterable.filter(filter).iterator();
        List<Document> documentList = new ArrayList<Document>();
        while (mongoCursor.hasNext()) {
            Document document = mongoCursor.next();
            documentList.add(document);
        }
        return documentList;
    }

    public void updateOne(String collection, Document document) {
        Document query = new Document();
        query.put("_id", new ObjectId(document.get("_id").toString()));
        document.remove("_id");
        Document updateDoc = new Document();
        updateDoc.put("$set", document);
        mongoTemplate.getCollection(collection).updateOne(query, updateDoc);
    }

    private Document handelId(Bson bson) {
        if (bson != null) {
            Document document = (Document) bson;
            Object id = null;
            if (document.containsKey("id")) {
                id = document.get("id");
                document.remove("id");
            } else if (document.containsKey("_id")) {
                id = document.get("_id");
            }
            if (id != null) {
                ObjectId objId = new ObjectId(id.toString());
                document.put("_id", objId);
            }
            return document;
        }
        return new Document();
    }
}

4、测试类(用法参考)

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Transactional    // 注释后回滚
class MongoDBTest {
    @Autowired
    private MongoUtils mongoUtils;

    @BeforeEach
    void setUp() {
    }

    @AfterEach
    void tearDown() {
    }

    @Test
    void insertOne() {
        Document doc = new Document();
        doc.put("name", "world");
        doc.put("age", 16);
        mongoUtils.insertOne("collection", doc);
    }

    @Test
    void insertMany() {
        List<Document> documentList = new ArrayList<Document>();
        Document doc = new Document();
        doc.put("name", "sam");
        doc.put("age", 30);
        documentList.add(doc);
        doc = new Document();
        doc.put("name", "nicole");
        doc.put("age", 30);
        documentList.add(doc);
        mongoUtils.insertMany("collection", documentList);
    }

    @Test
    void findById() {
        System.out.println(mongoUtils.findById("collection", "5db7a5e66957f95f2a7459a6"));
    }

    @Test
    void updateOne() {
        Document doc = mongoUtils.findById("collection", "5db7a5e66957f95f2a7459a6");
        doc.replace("name", "Jully");
        mongoUtils.updateOne("collection", doc);
    }

    @Test
    void findOne() {
        Document doc = new Document();
        doc.put("name", "hello");
        System.out.println(mongoUtils.findOne("collection", doc));
    }

    @Test
    void findMany() {
        Document doc = new Document();
        doc.put("id", "5db7a5e66957f95f2a7459a6");
        System.out.println(mongoUtils.findMany("collection", doc));
    }

    @Test
    void findAll() {
        System.out.println(mongoUtils.findAll("collection"));
    }
}

如果有问题,欢迎反馈。

posted @ 2019-12-25 15:58  御简  阅读(1630)  评论(0编辑  收藏  举报