Operation of the tools MongoDB

1. configuration file:

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

2. On Tools

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. Paging categories:

Package Penalty for com.shopping.app.util; 

Import java.util.List;
 Import java.util.Map; 


public  class PageBean { 

    Private List List;         // list of records to be returned to a page 

    Private  int allRow;          // total record number of 
    Private  int TotalPage;         // pages 
    Private  int currentPage;     // current page 
    Private  int pageSize;         // page number of records 

    Private  boolean isFirstPage;     // whether the first page of the 
    Private  booleanisLastPage;         // is the last one 
    Private  Boolean hasPreviousPage;     // if there is a front 
    Private  Boolean hasNextPage;         // if a next 


    public List the getList () {
         return List; 
    } 
    public  void setList (List List) {
         the this = .list List; 
    } 
    public  int getAllRow () {
         return allRow; 
    } 
    public  void setAllRow ( int allRow) {
         the this .allRow =  allRow;
    }
    public int getTotalPage() {
        return totalPage;
    }
    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
    public int getCurrentPage() {
        return currentPage;
    }
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    public int getPageSize() {
        return pageSize;
    }
    public voidsetPageSize ( int the pageSize) {
         the this .pageSize = the pageSize; 
    } 

    / **  * ** // 
     * initialize the paging information 
     * / 
    public  void the init () {
         the this .isFirstPage = isFirstPage ();
         the this .isLastPage = isLastPage ();
         the this = .hasPreviousPage isHasPreviousPage ();
         the this .hasNextPage = isHasNextPage (); 
    } 

    / **  * // ** 
     * the determined information page, just getter method (is method) to 
     * @return 
     * / 

    public  BooleanisFirstPage () {
         return The currentPage ==. 1;     // case of this page is the first page. 1 
    }
     public  Boolean isLastPage () {
         return The currentPage == TotalPage;     // if this page is the last page 
    }
     public  Boolean isHasPreviousPage () {
         return The currentPage ! = 1;         // long as this page is not a page 1 
    }
     public  Boolean isHasNextPage () {
         return The currentPage = TotalPage;!     // long as this page is not the last one 
    } 


    / **  * ** @ 
     * to calculate the total number of pages, static methods for external calls directly through the class name 
     *@param the pageSize per page recording 
     * @param total number of records allRow 
     * @return Pages
      * / 
    public  static  int countTotalPage ( Final  int the pageSize, Final  int allRow) {
         int TotalPage = (% allRow the pageSize == 0 && allRow! = ? 0) allRow / pageSize: allRow / pageSize + 1 ;
         return TotalPage; 
    } 

    / **  * // ** 
     * calculate the current page to start recording 
     * @param pageSize number of records per page 
     * @param currentPage current first few pages 
     * @returnThis page start record number
      * / 
    public  static  int countOffset ( Final  int the pageSize, Final  int The currentPage) {
         Final  int offset;
         IF (The currentPage == 0 ) { 
            offset = 0 ; 
        } the else { 
            offset = the pageSize * (The currentPage-. 1 ); 
        } 
        return offset; 
    } 

    / **  * ** // 
     * calculate this page, URL or 0 if it is not requested, then replaced with a "page =?" 
     * @param page parameters passed (possibly empty, i.e. 0, 1 is returned) 
     *@return 当前页
     */
    public static int countCurrentPage(int page){
        final int curPage = (page==0?1:page);
        return curPage;
    }

    public static String queryStr(Map<String, String> queryMap) {
        if(null!=queryMap){
            String queryUrl="";
            for(Map.Entry<String, String> qm : queryMap.entrySet()){
                if(qm.getValue()!=null && !qm.getValue().equals("") && qm.getValue().length()>0){
                    queryUrl += "&query." + qm.getKey()+"=" + qm.getValue();
                }
            }
            return queryUrl;
        }
        return "";
    }


}

Note: The need to introduce a package

Guess you like

Origin www.cnblogs.com/wyf-love-dch/p/10981026.html