• IDEA链接MongoDB数据库-实现增删改查


    中间出了一系列莫名其妙的问题,又莫名其妙地好了。

    这是我的配置文件,有点乱:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.5.6</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.ya</groupId>
        <artifactId>oeder-logistics-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>oeder-logistics-demo</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>11</java.version>
        </properties>
        <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-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>4.0.2.RELEASE</version>
            </dependency>
            <!--spring data mongodb-->
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-mongodb</artifactId>
                <version>2.0.5.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.jetbrains</groupId>
                <artifactId>annotations</artifactId>
                <version>RELEASE</version>
                <scope>compile</scope>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <excludes>
                            <exclude>
                                <groupId>org.projectlombok</groupId>
                                <artifactId>lombok</artifactId>
                            </exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>

    还导了两个包:

    连接数据库:

    package com.ya;
    
    import com.mongodb.*;
    import com.mongodb.MongoClient;
    import com.mongodb.client.*;
    import org.bson.Document;
    import java.util.ArrayList;
    import java.util.List;
    public class MongoDBConnection {
    //不认证直接链接数据库
        public MongoClient getConn(){
            MongoClient mongoClient = new MongoClient("localhost",27017);
            //也可使用MongoClientURI
            // MongoClientURI mongoClientURI = new MongoClientURI("mongodb://localhost:27017");
            // MongoClient mongoClient = new MongoClient(mongoClientURI);
            return mongoClient;
    
        }
    
    //通过用户密码认证链接数据库
    
        public MongoClient getConnByCredit(){
            String name = "test";//用户名
            String dbName = "Test";//数据库名
            char [] pwd = "test".toCharArray();//用户密码(将字符串转换成字符数组)
            List<ServerAddress> addresses = new ArrayList<>();
            //服务器地址:链接地址,端口号
            ServerAddress address = new ServerAddress("localhost",27017);
            addresses.add(address);
            List<MongoCredential> credentials = new ArrayList<>();
            //认证方法需要三个参数,用户名,数据库名,用户密码
            MongoCredential credential = MongoCredential.createScramSha1Credential(name,dbName,pwd);
            credentials.add(credential);
            //创建链接对象
            MongoClient mongoClient = new MongoClient(addresses,credentials);
            return mongoClient;
        }
    
    
        //测试是否连接成功
    
        public static void main(String[] args) {
    
            MongoDBConnection mongoDBConnection = new MongoDBConnection();
            MongoDatabase mongoDatabase = null;
            //MongoClient mongoClient = mongoDBConnection.getConn();
             MongoClient mongoClient = mongoDBConnection.getConnByCredit();
            // 查询所有数据库名称
            MongoIterable<String> dbNameList = mongoClient.listDatabaseNames();
            System.out.println("查询所有数据库名称:");
            for(String dbName : dbNameList)
                System.out.println(dbName);
            //创建数据库对象
            mongoDatabase = mongoClient.getDatabase("Test");
            //查询Test数据库中所有集合名称
            MongoIterable<String> colNameList = mongoDatabase.listCollectionNames();
            System.out.println("查询Test数据库中所有集合名称:");
            for(String colName: colNameList)
                System.out.println(colName);
            //关闭连接
            mongoClient.close();
    
        }
    
    }

    结果:

     增删改查:

    package com.ya;
    
    import com.mongodb.MongoClient;
    import com.mongodb.MongoException;
    import com.mongodb.client.*;
    import com.mongodb.client.model.Filters;
    import org.bson.Document;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MongoTest {
    
        //查询指定数据库中所有集合
        public void selectCollection(MongoDatabase database) {
            try {
                //查询Test数据库中所有集合名称
                MongoIterable<String> colNameList = database.listCollectionNames();
                for (String colName : colNameList)
                    System.out.println(colName);
                System.out.println("[INFO] : Select collection success!");
            } catch (MongoException e) {
                e.printStackTrace();
                System.out.println("[ERROR] : Select collection field!");
            }
        }
    
        //新建集合
    
        public void createCollection(MongoDatabase database){
    
            try{
                //创建新集合
                database.createCollection("testCol");
                System.out.println("[INFO] : Create collection success!");
            }catch(MongoException e){
                e.printStackTrace();
                System.out.println("[ERROR] : Create collection field!");
            }
        }
    
        //删除集合
        public void deleteCollection(MongoDatabase database){
            try{
                //删除集合
                MongoCollection mongoCollection = database.getCollection("testCol");
                mongoCollection.drop();
                System.out.println("[INFO] : Drop collection success!");
            }catch(MongoException e){
                e.printStackTrace();
                System.out.println("[ERROR] : Drop collection field!");
            }
        }
    
        //查询文档数据
        public void selectData(MongoDatabase database){
            try{
                //获取数据库中的user集合
                MongoCollection<Document> collection = database.getCollection("user");
                //获取user集合中的文档
                FindIterable<org.bson.Document> iterable = collection.find();
                //通过迭代器遍历找到的文档中的信息
                MongoCursor<org.bson.Document> iterator = iterable.iterator();
                while(iterator.hasNext()){
                    System.out.println(iterator.next().toJson());
                }
                System.out.println("[INFO] : Select data success!");
            }catch(MongoException e){
                e.printStackTrace();
                System.out.println("[ERROR] : Select data field!");
            }
        }
    
        //插入数据
        public void insertData(MongoDatabase database){
            try {
                MongoCollection mongoCollection = database.getCollection("user");
                //一次插入一条数据
                Document document = new Document("user_id","4")
                        .append("user_name","test")
                        .append("user_pwd","test");
                mongoCollection.insertOne(document);
                //一次插入多条数据
                Document document1 = new Document("user_id","5")
                        .append("user_name","test")
                        .append("user_pwd","test1");
                Document document2 = new Document("user_id","6")
                        .append("user_name","test")
                        .append("user_pwd","test2");
                List<Document> documents = new ArrayList<>();
                documents.add(document1);
                documents.add(document2);
                mongoCollection.insertMany(documents);
                System.out.println("[INFO] : Insert data success!");
            }catch(MongoException e){
                e.printStackTrace();
                System.out.println("[ERROR] : Insert data field!");
            }
        }
    
        //修改数据
        public void updateData(MongoDatabase database){
            try {
                MongoCollection mongoCollection = database.getCollection("user");
                //修改满足条件的第一条数据
                mongoCollection.updateOne(Filters.eq("user_name","test"),new Document("$set",new Document("user_pwd","tttt")));
                //修改满足条件的所有数据
                mongoCollection.updateMany(Filters.eq("user_name","test"),new Document("$set",new Document("user_pwd","tttt")));
                System.out.println("[INFO] : Update data success!");
            }catch(MongoException e){
                e.printStackTrace();
                System.out.println("[ERROR] : Update data field!");
            }
        }
    
        //删除数据
        public void deleteData(MongoDatabase database){
            try {
                MongoCollection mongoCollection = database.getCollection("user");
                //删除满足条件的第一条记录
                mongoCollection.deleteOne(Filters.eq("user_name","test"));
                //删除满足条件的所有数据
                mongoCollection.deleteMany(Filters.eq("user_name","test"));
                System.out.println("[INFO] : Delete data success!");
            }catch(MongoException e){
                e.printStackTrace();
                System.out.println("[ERROR] : Delete data field!");
            }
        }
        public static void main(String args[]){
            MongoTest mongoTest =new MongoTest();
            MongoDBConnection mongoDBConnection = new MongoDBConnection();
            //新建链接
            MongoClient mongoClient = mongoDBConnection.getConn();
            //创建数据库对象
            MongoDatabase mongoDatabase = mongoClient.getDatabase("Test");
    
    
            //在Test里新建集合
            //mongoTest.createCollection(mongoDatabase);
    
            //删除集合
            //mongoTest.deleteCollection(mongoDatabase);
    
    
            //查询Test数据库中所有集合名称
            mongoTest.selectCollection(mongoDatabase);
    
            //插入数据
            //mongoTest.insertData(mongoDatabase);
    
            //修改数据
            //mongoTest.updateData(mongoDatabase);
    
            //删除数据
            //mongoTest.deleteData(mongoDatabase);
    
            //查询数据文档
            //mongoTest.selectData(mongoDatabase);
    
            //关闭连接
            mongoClient.close();
    
        }
    }
  • 相关阅读:
    C#注释含义(XML注释)标签及其含义(二)
    Apache开启伪静态[转]
    C#注释含义(XML注释)标签及其含义(一)
    [转]终结PHP中文乱码的问题
    Symfony框架百科/项目实战/指南/教程
    第一次用Office2007写博客
    prototype.js是什么?
    优秀网站源码 集合
    Pager 精简的分页控件
    Validator.js 很好用的客户端表单验证
  • 原文地址:https://www.cnblogs.com/j-y-s/p/15506762.html
Copyright © 2020-2023  润新知