1.配置文件:
#mongodb config mongo.host = 127.0.0.1 mongo.port = 27017 mongo.dbname = dk mongo.username = root mongo.password = 123456
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.app.util; import java.util.List; import java.util.Map; public class PageBean { private List list; //要返回的某一頁的記錄列表 private int allRow; //總記錄數 private int totalPage; //總頁數 private int currentPage; //當前頁 private int pageSize; //每頁記錄數 private boolean isFirstPage; //是否為第一頁 private boolean isLastPage; //是否為最后一頁 private boolean hasPreviousPage; //是否有前一頁 private boolean hasNextPage; //是否有下一頁 public List getList() { return list; } public void setList(List list) { this.list = list; } public int getAllRow() { return allRow; } public void setAllRow(int allRow) { 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 void setPageSize(int pageSize) { this.pageSize = pageSize; } /** *//** * 初始化分頁信息 */ public void init(){ this.isFirstPage = isFirstPage(); this.isLastPage = isLastPage(); this.hasPreviousPage = isHasPreviousPage(); this.hasNextPage = isHasNextPage(); } /** *//** * 以下判斷頁的信息,只需getter方法(is方法)即可 * @return */ public boolean isFirstPage() { return currentPage == 1; // 如是當前頁是第1頁 } public boolean isLastPage() { return currentPage == totalPage; //如果當前頁是最后一頁 } public boolean isHasPreviousPage() { return currentPage != 1; //只要當前頁不是第1頁 } public boolean isHasNextPage() { return currentPage != totalPage; //只要當前頁不是最后1頁 } /** *//** * 計算總頁數,靜態方法,供外部直接通過類名調用 * @param pageSize 每頁記錄數 * @param allRow 總記錄數 * @return 總頁數 */ public static int countTotalPage(final int pageSize,final int allRow){ int totalPage = (allRow % pageSize == 0 && allRow != 0) ? allRow/pageSize : allRow/pageSize+1; return totalPage; } /** *//** * 計算當前頁開始記錄 * @param pageSize 每頁記錄數 * @param currentPage 當前第幾頁 * @return 當前頁開始記錄號 */ public static int countOffset(final int pageSize,final int currentPage){ final int offset; if(currentPage == 0){ offset = 0; }else{ offset = pageSize*(currentPage-1); } return offset; } /** *//** * 計算當前頁,若為0或者請求的URL中沒有"?page=",則用1代替 * @param page 傳入的參數(可能為空,即0,則返回1) * @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 ""; } }
注意:需要引入包