不使用spring的情况下用java原生代码操作mongodb数据库的两种方式
由于更改了mongodb3.0数据库的密码,导致这几天storm组对数据进行处理的时候,一直在报mongodb数据库连接不上的异常。
主要原因实际上是和mongodb本身无关的,因为他们改的是配置文件的密码,而实际上这个密码在代码中根本就没有使用,他们在代码中已经把用户验证信息写死。
在协助他们解决这个问题的时候,我看到他们代码中在和mongodb数据库交互时使用了已经不被建议使用的方法,于是便抽时间尝试了一下另一种被建议的方式实现各功能。
当然了,生产环境中用的是mongodb集群,验证时的写法和单机时会略有不同,我这里就只拿单机试验。
使用原生的Java代码操作mongodb数据库,就不需要和spring集成的那些jar包,只用到了mongodb-java-driver3.0.3.jar,代码如下,一些需要注意的地方也都写在注释中:
- package monAndMysql;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.Set;
- import org.bson.BsonDocument;
- import org.bson.BsonString;
- import org.bson.Document;
- import org.bson.conversions.Bson;
- import com.mongodb.BasicDBObject;
- import com.mongodb.DB;
- import com.mongodb.DBCollection;
- import com.mongodb.DBCursor;
- import com.mongodb.DBObject;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- import com.mongodb.client.model.Filters;
- /**
- * mongodb和mysql性能测试
- *
- * @author tuzongxun123
- *
- */
- public class MonAndMysqlTest {
- public static void main(String[] args) {
- mongodbTest();
- }
- public static void mongodbTest() {
- ServerAddress sa = new ServerAddress("192.168.0.7", 27017);
- List<MongoCredential> mongoCredentialList = newArrayList<MongoCredential>();
- // java代码连接mongodb3.0数据库验证,userName,dbName,password
- mongoCredentialList.add(MongoCredential.createMongoCRCredential(
- "admin", "admin", "123456".toCharArray()));
- MongoClient client = new MongoClient(sa, mongoCredentialList);
- // 第一种方式
- // 第一种方式获取db,该方法已经不建议使用
- DB mongoDB = client.getDB("mongoTest1");
- DBCollection collection1 = mongoDB.getCollection("userTest1");
- // 这里的数据类型是dbobject
- DBObject document1 = new BasicDBObject();
- document1.put("name", "mongoTest1");
- document1.put("createTime", new Date().getTime());
- // 插入数据
- collection1.insert(document1);
- // 查询数据
- DBCursor cursor1 = collection1.find();
- System.out.println("第一种方式插入数据的结果:");
- while (cursor1.hasNext()) {
- DBObject object = cursor1.next();
- Set<String> keySet = object.keySet();
- for (String key : keySet) {
- System.out.println(key + ":" + object.get(key));
- }
- }
- // 更改数据
- DBObject query = new BasicDBObject();
- DBObject update = new BasicDBObject();
- query.put("name", "mongoTest1");
- update.put("$set", new BasicDBObject("name", "update1"));
- collection1.update(query, update);
- System.out
- .println("--------------------------------------------------------------------------------------");
- System.out.println("第一种方式修改数据的结果:");
- DBCursor cursor11 = collection1.find();
- while (cursor11.hasNext()) {
- DBObject object = cursor11.next();
- Set<String> keySet = object.keySet();
- for (String key : keySet) {
- System.out.println(key + ":" + object.get(key));
- }
- }
- // 删除数据
- DBObject query1 = new BasicDBObject();
- query1.put("name", "update1");
- collection1.remove(query1);
- System.out
- .println("--------------------------------------------------------------------------------------");
- System.out.println("第一种方式删除数据的结果:");
- DBCursor cursor12 = collection1.find();
- while (cursor12.hasNext()) {
- DBObject object = cursor12.next();
- Set<String> keySet = object.keySet();
- for (String key : keySet) {
- System.out.println(key + ":" + object.get(key));
- }
- }
- // 第二种方式
- System.out
- .println("****************************************************************************");
- // 第二种方式获取db及插入数据和查询操作。推荐方式
- MongoDatabase database = client.getDatabase("mongoTest2");
- // 注意这里的数据类型是document
- Document document2 = new Document();
- document2.put("name", "mongoTest2");
- document2.put("createTime", new Date().getTime());
- MongoCollection collection2 = database.getCollection("userTest2");
- // 插入数据
- collection2.insertOne(document2);
- // 查询数据,注意这里直接查询出的结果不是游标,还需要转换
- FindIterable<Document> findIterable = collection2.find();
- MongoCursor<Document> cursor2 = findIterable.iterator();
- System.out.println("第二种方式插入数据的结果:");
- while (cursor2.hasNext()) {
- Document document = cursor2.next();
- Set<String> keySet = document.keySet();
- for (String key : keySet) {
- System.out.println(key + ":" + document.get(key));
- }
- }
- // 更改数据
- Bson filter = Filters.eq("name", "mongoTest2");
- BsonDocument update2 = new BsonDocument();
- update2.put("$set", new BsonDocument("name", new BsonString("update2")));
- collection2.updateOne(filter, update2);
- System.out
- .println("--------------------------------------------------------------------------------------");
- MongoCursor<Document> cursor21 = findIterable.iterator();
- System.out.println("第二种方式更改数据的结果:");
- while (cursor21.hasNext()) {
- Document document = cursor21.next();
- Set<String> keySet = document.keySet();
- for (String key : keySet) {
- System.out.println(key + ":" + document.get(key));
- }
- }
- // 删除数据
- Bson filter2 = Filters.eq("name", "update2");
- collection2.deleteOne(filter2);
- System.out
- .println("--------------------------------------------------------------------------------------");
- MongoCursor<Document> cursor22 = findIterable.iterator();
- System.out.println("第二种方式删除数据的结果:");
- while (cursor22.hasNext()) {
- Document document = cursor22.next();
- Set<String> keySet = document.keySet();
- for (String key : keySet) {
- System.out.println(key + ":" + document.get(key));
- }
- }
- // 关闭数据库连接
- client.close();
- }
- }
执行main方法后,控制台打印结果如下图所示,证明操作都是没有问题的:
不使用spring的情况下用java原生代码操作mongodb数据库的两种方式的更多相关文章
- JAVA发送http GET/POST请求的两种方式+JAVA http 请求手动配置代理
java发送http get请求,有两种方式. 第一种用URLConnection: public static String get(String url) throws IOException { ...
- java中读取配置文件ResourceBundle和Properties两种方式比较
今天在开发的时候,需要把一些信息放到配置文件中,方便后续的修改,注意到用的是ResourceBundle读取配置文件的方式,记得之前也见过使用Properties的方式,就比较好奇这两种方式的区别,网 ...
- 依赖Spring的情况下,Java Web项目如何在启动时加载数据库中的数据?
原文:https://blog.csdn.net/u012345283/article/details/39558537 原文:https://blog.csdn.net/wandrong/artic ...
- windows下配置tomcat服务器的jvm内存大小的两种方式
难得遇到一次java堆内存溢出(心里想着,终于可以来一次jvm性能优化了$$) 先看下报错信息, java.lang.OutOfMemoryError: GC overhead limit excee ...
- Linux下chkconfig命令详解即添加服务以及两种方式启动关闭系统服务
The command chkconfig is no longer available in Ubuntu.The equivalent command to chkconfig is update ...
- java操作excel常用的两种方式
Excel是我们平时工作中比较常用的用于存储二维表数据的,JAVA也可以直接对Excel进行操作,在这篇博客中将为大家介绍两种操作Excel的方式,分别为:jxl和poi. 对于两者的区别网上有测试如 ...
- java后台处理解析json字符串的两种方式
简单说一下背景 上次后端通过模拟http请求百度地图接口,得到的是一个json字符串,而我只需要其中的某个key对应的value. 当时我是通过截取字符串取的,后来觉得不太合理,今天整理出了两种处理解 ...
- Java代码模拟http请求的两种方式
z这里用百度地图的逆地理编码接口为例, 第一种方式:(通过jdk中的java.net包) 引入工具类 import java.net.URL; import java.net.URLConnectio ...
- Spring框架访问数据库的两种方式的小案例
1.1 以Xml的方式访问数据库的案例 要以xml的方式访问数据库需要用到JdbcTemplate ,因为 JdbcTemplate(jdbc的模板对象)在Spring 中提供了一个可以操作数据库的对 ...
随机推荐
- MySQL笔记-union
union语法 select ... union [all | distinct] selct ... union用于把来自多个select语句的结果组合在一个结果集中. 两次查询的列表必须相同,否则 ...
- vue2.0开发时导入组件时出错
导入自定义组件时出现了如下错误 ERROR Failed to compile with 1 errors 12:35:41 This dependency was not found: * comp ...
- 洛谷 [P1963] [NOI2009] 变换序列
这是一道二分图匹配的题 先%dalao博客 建图并没有什么难的,但是关键在于如何使字典序最小. 一个很显然的想法是先求出一个完美匹配,然后从x集合的第一个元素开始,如果该元素匹配的较小的一个,那么继续 ...
- BZOJ 1969: [Ahoi2005]LANE 航线规划 [树链剖分 时间倒流]
题意: 一张图,删除边,求两点之间的割边数量.保证任意时刻图连通 任求一棵生成树,只有树边可能是割边 时间倒流,加入一条边,就是两点路径上的边都不可能是割边,区间覆盖... 然后本题需要把边哈希一下, ...
- Heartbeat实现热备
1.环境准备:1)主节点:master eth0:192.168.0.201 eth1:192.168.0.03 2)备节点:slave eth0 :192.168.0.215 eth1:192.16 ...
- c# Nlog 非xml cs方法配置
public static void InitLog(TargetWithLayout target = null, string level = "Debug", string ...
- 使用VS Code开发asp.net core (下)
第一部分: https://www.cnblogs.com/cgzl/p/8450179.html 本文是基于Windows10的. Debugging javascript 打开wwwroot/js ...
- 打通MySQL的操作权限
打通MySQL的操作权限 前面已经总结了<XAMPP的配置与使用>,虽然可以直接通过GUI控制面板去启动MySQL服务,但是有些相关的操作则需要在Windows中的CMD命令窗口中去对My ...
- window.location的路径
1 相对路径 window.location.href='add_affiche.php'; 或 window.location.href='./add_affiche.php'; 2 绝对路径 wi ...
- shell脚本实现anisble客户端脚本分发和密钥授权配置
##############################Deploy ansible client shell######################## echo "start d ...