Java单例模式下的MongoDB数据库操作工具类
作者:Constantin 发布时间:2023-11-20 12:55:01
标签:Java,单例模式,MongoDB
本文实例讲述了Java单例模式下的MongoDB数据库操作工具类。分享给大家供大家参考,具体如下:
我经常对MongoDB进行一些基础操作,将这些常用操作合并到一个工具类中,方便自己开发使用。
没用Spring Data、Morphia等框架是为了减少学习、维护成本,另外自己直接JDBC方式的话可以更灵活,为自己以后的积累留一个脚印。
JAVA驱动版本:
<!-- MongoDB驱动 -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.2</version>
</dependency>
工具类代码如下:
package utils;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
/**
* MongoDB工具类 Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够了<br>
* 注意Mongo已经实现了连接池,并且是线程安全的。 <br>
* 设计为单例模式, 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,<br>
* Mongo有个内置的连接池(默认为10个) 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,<br>
* DB和DBCollection是绝对线程安全的<br>
*
* @author zhoulingfei
* @date 2015-5-29 上午11:49:49
* @version 0.0.0
* @Copyright (c)1997-2015 NavInfo Co.Ltd. All Rights Reserved.
*/
public enum MongoDBUtil {
/**
* 定义一个枚举的元素,它代表此类的一个实例
*/
instance;
private MongoClient mongoClient;
static {
System.out.println("===============MongoDBUtil初始化========================");
CompositeConfiguration config = new CompositeConfiguration();
try {
config.addConfiguration(new PropertiesConfiguration("mongodb.properties"));
} catch (ConfigurationException e) {
e.printStackTrace();
}
// 从配置文件中获取属性值
String ip = config.getString("host");
int port = config.getInt("port");
instance.mongoClient = new MongoClient(ip, port);
// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
// List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018));
// instance.mongoClient = new MongoClient(listHost);
// 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:
// boolean auth = db.authenticate(myUserName, myPassword);
Builder options = new MongoClientOptions.Builder();
// options.autoConnectRetry(true);// 自动重连true
// options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100
options.connectTimeout(15000);// 连接超时,推荐>3000毫秒
options.maxWaitTime(5000); //
options.socketTimeout(0);// 套接字超时时间,0无限制
options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
options.writeConcern(WriteConcern.SAFE);//
options.build();
}
// ------------------------------------共用方法---------------------------------------------------
/**
* 获取DB实例 - 指定DB
*
* @param dbName
* @return
*/
public MongoDatabase getDB(String dbName) {
if (dbName != null && !"".equals(dbName)) {
MongoDatabase database = mongoClient.getDatabase(dbName);
return database;
}
return null;
}
/**
* 获取collection对象 - 指定Collection
*
* @param collName
* @return
*/
public MongoCollection<Document> getCollection(String dbName, String collName) {
if (null == collName || "".equals(collName)) {
return null;
}
if (null == dbName || "".equals(dbName)) {
return null;
}
MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
return collection;
}
/**
* 查询DB下的所有表名
*/
public List<String> getAllCollections(String dbName) {
MongoIterable<String> colls = getDB(dbName).listCollectionNames();
List<String> _list = new ArrayList<String>();
for (String s : colls) {
_list.add(s);
}
return _list;
}
/**
* 获取所有数据库名称列表
*
* @return
*/
public MongoIterable<String> getAllDBNames() {
MongoIterable<String> s = mongoClient.listDatabaseNames();
return s;
}
/**
* 删除一个数据库
*/
public void dropDB(String dbName) {
getDB(dbName).drop();
}
/**
* 查找对象 - 根据主键_id
*
* @param collection
* @param id
* @return
*/
public Document findById(MongoCollection<Document> coll, String id) {
ObjectId _idobj = null;
try {
_idobj = new ObjectId(id);
} catch (Exception e) {
return null;
}
Document myDoc = coll.find(Filters.eq("_id", _idobj)).first();
return myDoc;
}
/** 统计数 */
public int getCount(MongoCollection<Document> coll) {
int count = (int) coll.count();
return count;
}
/** 条件查询 */
public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
return coll.find(filter).iterator();
}
/** 分页查询 */
public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) {
Bson orderBy = new BasicDBObject("_id", 1);
return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();
}
/**
* 通过ID删除
*
* @param coll
* @param id
* @return
*/
public int deleteById(MongoCollection<Document> coll, String id) {
int count = 0;
ObjectId _id = null;
try {
_id = new ObjectId(id);
} catch (Exception e) {
return 0;
}
Bson filter = Filters.eq("_id", _id);
DeleteResult deleteResult = coll.deleteOne(filter);
count = (int) deleteResult.getDeletedCount();
return count;
}
/**
* FIXME
*
* @param coll
* @param id
* @param newdoc
* @return
*/
public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) {
ObjectId _idobj = null;
try {
_idobj = new ObjectId(id);
} catch (Exception e) {
return null;
}
Bson filter = Filters.eq("_id", _idobj);
// coll.replaceOne(filter, newdoc); // 完全替代
coll.updateOne(filter, new Document("$set", newdoc));
return newdoc;
}
public void dropCollection(String dbName, String collName) {
getDB(dbName).getCollection(collName).drop();
}
/**
* 关闭Mongodb
*/
public void close() {
if (mongoClient != null) {
mongoClient.close();
mongoClient = null;
}
}
/**
* 测试入口
*
* @param args
*/
public static void main(String[] args) {
String dbName = "GC_MAP_DISPLAY_DB";
String collName = "COMMUNITY_BJ";
MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
// 插入多条
// for (int i = 1; i <= 4; i++) {
// Document doc = new Document();
// doc.put("name", "zhoulf");
// doc.put("school", "NEFU" + i);
// Document interests = new Document();
// interests.put("game", "game" + i);
// interests.put("ball", "ball" + i);
// doc.put("interests", interests);
// coll.insertOne(doc);
// }
// // 根据ID查询
// String id = "556925f34711371df0ddfd4b";
// Document doc = MongoDBUtil2.instance.findById(coll, id);
// System.out.println(doc);
// 查询多个
// MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();
// while (cursor1.hasNext()) {
// org.bson.Document _doc = (Document) cursor1.next();
// System.out.println(_doc.toString());
// }
// cursor1.close();
// 查询多个
// MongoCursor<Person> cursor2 = coll.find(Person.class).iterator();
// 删除数据库
// MongoDBUtil2.instance.dropDB("testdb");
// 删除表
// MongoDBUtil2.instance.dropCollection(dbName, collName);
// 修改数据
// String id = "556949504711371c60601b5a";
// Document newdoc = new Document();
// newdoc.put("name", "时候");
// MongoDBUtil.instance.updateById(coll, id, newdoc);
// 统计表
// System.out.println(MongoDBUtil.instance.getCount(coll));
// 查询所有
Bson filter = Filters.eq("count", 0);
MongoDBUtil.instance.find(coll, filter);
}
}
希望本文所述对大家java程序设计有所帮助。
来源:https://www.cnblogs.com/zhoulf/p/4571647.html


猜你喜欢
- 1. 为什么要更改SpringBoot运行方式?Tomcat Connector(连接器)有三种运行模式:bio nio aprbio(bl
- 本文实例讲述了java实现的n*n矩阵求值及求逆矩阵算法。分享给大家供大家参考,具体如下:先来看看运行结果:java版的写出来了,用的跟c语
- 目录概览问题一原因解决办法问题二原因解决办法概览在当下几乎所有的公司都采用了前后端分离的开发模式,Swagger作为了在API在线文档工具,
- 在web应用中,常常会遇见点击某个链接会弹出一个新的窗口,或者是相互关联的web应用 ,这样要去操作新窗口中的元素,就需要主机切换到新窗口进
- Java.lang 中自带的注解@Override:表示当前的方法定义将覆盖基类的方法。如果你不小心拼写错误,或者方法签名被错误拼写的时候,
- 前言这周接到一个需求,需要在应用从后台切换到前台时,展示我们的广告。展示页面其实可以复用以前的开屏广告页,唯一的问题就是如何监听应用从后台切
- Unity中,我们怎么制作UI物体发光的渐隐渐现的效果呢?比如说我们有一张月亮光晕的精灵图片我们可以给它添加一个CanvasGroup组件我
- Android Studio常用快捷键、Android Studio快捷键大全接下来这篇android studio使用教程,主要为大家介绍
- 1.static静态变量1.静态变量被同一个类的所有对象共享2.static类变量在类加载的时候就生成使用static保存在class实例的
- 一、# List泛型集合集合是OOP中的一个重要概念,C#中对集合的全面支持更是该语言的精华之一。为什么要用泛型集合?在C# 2.0之前,主
- 在作应用系统开发时,管理配置是必不可少的。例如数据库服务器的配置、安装和更新配置等等。由于Xml的兴起,现在的配置文件大都是以xml文档来存
- 最新idea2020安装部署超详细教程懂得懂的2020.32020.2.42020.2.32020.2.220.2.12019.32018.
- 一、遇到一个问题1、读取CSV文件package com.guor.demo.charset;import java.io.Buffered
- 初次接触spring-boot的时候,我们经常会看到这样的文章:“
- 前言最近测试给我提了一个bug,说我之前提供的一个批量复制商品的接口,产生了重复的商品数据。追查原因之后发现,这个事情没想象中简单,可以说一
- 相关文章:Java使用POI导出Excel(一):单sheetJava使用POI导出Excel(二):多个sheet相信在大部分的web项目
- 简述mysq5.7之后新增了json类型,但是在使用的过程中,Json数组中的值小于Integer.MAX_VALUE,则反序列化时会转成L
- 现在很多网站都有注册登录的页面,为了更好的满足用户体验和网站的安全性,很多网站都采用动态生成的图形码或者是附加码进行验证,下面把生成验证码的
- Intent应该算是Android * 有的东西。你可以在Intent中指定程序要执行的动作(比如:view,edit,dial),以及程序执
- 目录Maven依赖配置示例Maven依赖要开始使用咖啡因Caffeine和Spring Boot,我们首先添加spring-boot-sta