zoukankan      html  css  js  c++  java
  • Mangodb的工具类操作数据库

        Mangodb是面向文档存储的数据库,操作起来比较简单。存储数据使用的是BSON字符串的key-value的形式存储。

    mangodb主要常用函数有:insert (插入数据)、update/save(更改)、find()、remove(删除数据)。

         1.配置文件:mongodb.properties

       

    #mongodb config
    mongo.host = 127.0.0.1
    mongo.port = 27017
    mongo.dbname = dk
    mongo.username = dk
    mongo.password = dk2018
    

      

     2.工具类:

    package com.shopping.core.base;
    
    
    import com.mongodb.*;
    import com.mongodb.client.FindIterable;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoCursor;
    import com.mongodb.client.MongoDatabase;
    import com.shopping.app.util.PageBean;
    
    import org.bson.BSONObject;
    import org.bson.BasicBSONObject;
    import org.bson.Document;
    
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.*;
    
    
    public  class BaseDaoRepository{
    
        private static Properties properties;
    
        private static MongoDatabase mongoDatabase;
    
    
        public static MongoDatabase getConnectInfo(){
            if(properties==null){
                properties=new Properties();
            }
    
            InputStream stream = null;
            try {
                stream = BaseDaoRepository.class.getClassLoader()
                        .getResourceAsStream("mongodb.properties");
                properties.load(stream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 获取key对应的value值
            String host=properties.getProperty("mongo.host");
            int port=Integer.parseInt(properties.getProperty("mongo.port"));
            String dbname=properties.getProperty("mongo.dbname");
            String username=properties.getProperty("mongo.username");
            String password=properties.getProperty("mongo.password");
            ServerAddress serverAddress = new ServerAddress(host,port);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);
            MongoCredential credential = MongoCredential.createScramSha1Credential(dbname, username, password.toCharArray());
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(credential);
            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(addrs,credentials);
            //连接到数据库
            mongoDatabase = mongoClient.getDatabase(dbname);
            return mongoDatabase;
        }
    
        public static PageBean getData(int pageSize, int page, Document query,String c){
            List<Document> list=new ArrayList<>();
            if (mongoDatabase==null){
                getConnectInfo();
            }
            final int offset = PageBean.countOffset(pageSize, page);
            final int length = pageSize;
            MongoCollection<Document> collection=mongoDatabase.getCollection(c);
            Document document=new Document("timestamp",1);
            FindIterable<Document> findIterable = collection.find(query).sort(document);
            MongoCursor<Document> mongoCursor = findIterable.iterator();
            while(mongoCursor.hasNext()){
                Document d=mongoCursor.next();
                list.add(d);
            }
            int allRow = list.size();
            int totalPage = PageBean.countTotalPage(pageSize, allRow);
            final int currentPage = PageBean.countCurrentPage(page);
            PageBean pageBean = new PageBean();
            pageBean.setPageSize(pageSize);
            pageBean.setCurrentPage(currentPage);
            pageBean.setAllRow(allRow);
            pageBean.setTotalPage(totalPage);
            int start=(page-1)*pageSize;
            int end=(page*pageSize);
            if (end>allRow){
                end=allRow;
            }
            List newList = list.subList(start, end);
            pageBean.setList(newList);
            pageBean.init();
            return pageBean;
        }
    
        public static void insert(String c,List<Document> documents){
            if (mongoDatabase==null){
                getConnectInfo();
            }
            MongoCollection<Document> collection=mongoDatabase.getCollection(c);
            collection.insertMany(documents);
            System.out.println("文档插入成功");
        }
    
        public static Document getOneById(Document query,String c){
            if (mongoDatabase==null){
                getConnectInfo();
            }
            MongoCollection<Document> collection=mongoDatabase.getCollection(c);
            FindIterable<Document> findIterable = collection.find(query);
            MongoCursor<Document> mongoCursor = findIterable.iterator();
            Document d=null;
            while(mongoCursor.hasNext()){
                d=mongoCursor.next();
            }
            return d;
        }
    
        public static void update(String c,Document query,Document document){
            if (mongoDatabase==null){
                getConnectInfo();
            }
            MongoCollection<Document> collection=mongoDatabase.getCollection(c);
            collection.updateOne(query,document);
            System.out.println("文档更新成功");
        }
    
    
        public static void main( String args[] ){
    
        }
    
    
    
    }

    3 .测试操作数据库

    package com.shopping.test;
    
    import com.shopping.app.util.PageBean;
    import com.shopping.core.base.BaseDaoRepository;
    import net.sf.json.JSONArray;
    import org.bson.Document;import java.util.*;
    
    /**
     * 测试redis缓存 芒果数据库的插入 查询测试
     */
    public class RedisTest {
    
        public static void main(String[] args) {
    
            //新增MongoDB 数据表
            List<Document> documents = new ArrayList<Document>();
            Date date = new Date();
            String timestampBody = String.valueOf(date.getTime());
            String chat_type = "chatTest";
            String from = "35920";
            String to = "368923";
            String msg_id = "12";
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //生成文件
            Document document = new Document().
                    append("timestamp", timestampBody).
                    append("chat_type", chat_type).
                    append("from", from).append("to", to).append("msg_id", msg_id).append("uuid", uuid);
            documents.add(document);
            BaseDaoRepository.insert("chatRecord_test", documents);
    
    
            /**
             * 分页查询
             */
            int page = 1;
            //根据条件查询数据库
            Document documentQU = new Document("to", "368923").append("chat_type", "chatTest");
            //用到了MongoDB  查询数据
            PageBean pageBean = BaseDaoRepository.getData(8, page, documentQU, "chatRecord_test");
            System.out.println(pageBean.getList());
            List<Document> documentQUs = pageBean.getList();
            for (Document dc : documentQUs) {
                JSONArray jsonArray = JSONArray.fromObject(dc);
                System.out.println(jsonArray);
                System.out.println(dc.get("_id").toString());
            }
    
            /***
             * 单个查询
             */
            String uUid = "3d16c5275cc74a6fa7f67ca0c4704546";
            Document query = new Document("uuid", uUid);
            Document result = BaseDaoRepository.getOneById(query, "chatRecord_test");
            String time = result.get("timestamp").toString();
            System.out.println("time" + time);
    
    
            /**
             * 修改操作
             */
            result.append("to", 1);
            BaseDaoRepository.update("chatRecord_test", query, result);
    
        }
    
    
    }
  • 相关阅读:
    简易sql拼接工具类(使用StringBuilder实现)
    缓存工具类(使用ConcurrentMap集合实现)
    properties文档读取工具类
    【Codeforces Round #655 (Div. 2)】A-D
    【2020 杭电多校第四场】Go Running 最小点覆盖
    【2020 杭电多校第四场】1002 Blow up the Enemy
    【2020 HDU 多校训练第三场 1007 Tokitsukaze and Rescue】暴力删边&最短路
    【2020杭电多校第二场】Total Eclipse 思维+并查集
    【2020HDU多校】Lead of Wisdom 暴力
    【CF-1371 C-E2】
  • 原文地址:https://www.cnblogs.com/wyf-love-dch/p/11056849.html
Copyright © 2011-2022 走看看