Java使用mongodb原生增删改查语句

2018-03-16

自动化测试时,需校验数据库数据,为了快速自动化,在代码中用原生增删改查语句操作mongodb

结构

代码

0 pom.xml

  <dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
</dependencies>

1 客户端操作Client.java

package com.mongodb.util;

import com.mongodb.util.DBConnection.DriverName;

public class Client {

    public static void main(String[] args) {
DBConnection conn = new DBConnection();
conn.setDbConnectionName("mongoDb1");
conn.setSource("****");
conn.setDbName("****");
conn.setDriverName(DriverName.mongodb);
conn.setServerHost("****");
conn.setServerPort("27017");
conn.setUserName("****");
conn.setPassword("****");
String querySqlWithFields = "db.getCollection('laAppInterface').find({$or:[{'appCode':'100005'},{'appCode':'10005'}]},{'appCode':1,'interfaceId':1})";
String querySqlWithoutFields = "db.getCollection('laAppInterface').find({$or:[{'appCode':'100005'},{'appCode':'10005'}]})"; Crud.Connect(conn); //注意:客户端工具Robomogon中,保存整数1,要用NumberInt(1),否则会变成1.0
String create = "db.getCollection('laAppInterface').save({'appCode':'10005','interfaceId':'TEST-API-0000068','invokeType':1,'callbackAddress':'',})";
System.out.println("Create: "+Crud.OperateDB(create,false));
System.out.println(Crud.OperateDB(querySqlWithFields, false));
System.out.println(Crud.OperateDB(querySqlWithFields, true));
System.out.println(Crud.OperateDB(querySqlWithoutFields, false));
System.out.println(Crud.OperateDB(querySqlWithoutFields, true));
String update="db.getCollection('laAppInterface').update({'interfaceId':'TEST-API-0000068'},{$set:{'appCode':'100005'}});";
System.out.println("Update: "+Crud.OperateDB(update,false));
System.out.println(Crud.OperateDB(querySqlWithFields, false)); String delete="db.getCollection('laAppInterface').remove({$or:[{'appCode':'100005'},{'appCode':'10005'}]});";
System.out.println("Delete: "+Crud.OperateDB(delete,false));
System.out.println(Crud.OperateDB(querySqlWithFields, false)); //比较运算
String queryGt="db.getCollection('laAppInterface').find({'invokeType':{$gt:1}},{'appCode':1,'invokeType':1})";
System.out.println("queryGt: "+Crud.OperateDB(queryGt, false)); //暂不支持模糊查询 {'appCode':/0005/}
}
}

执行结果:

Create: 0
[["10005","TEST-API-0000068"]]
[{"appCode":"10005","interfaceId":"TEST-API-0000068"}]
[[{"counter":7184126,"date":1521186717000,"machineIdentifier":7002056,"processIdentifier":13740,"time":1521186717000,"timeSecond":1521186717,"timestamp":1521186717},"10005","TEST-API-0000068",1,""]]
[{"_id":{"counter":7184126,"date":1521186717000,"machineIdentifier":7002056,"processIdentifier":13740,"time":1521186717000,"timeSecond":1521186717,"timestamp":1521186717},"appCode":"10005","interfaceId":"TEST-API-0000068","invokeType":1,"callbackAddress":""}]
Update: 1
[["100005","TEST-API-0000068"]]
Delete: 1
[]
queryGt: [["1002",4],["1002",4],["1002",4],["1002",4],["1002",4],["1004",4],["1002",4],["1002",4],["1002",4],["1002",4],["1001",4],["1001",4],["1001",4],["1001",4],["1001",4]]

2 mongodb增删改查操作Crud.java

只暴露两个方法

public static void Connect(DBConnection dbCon);
public static String OperateDB(String sql, Boolean hasColumnName);
package com.mongodb.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;
import com.mongodb.util.DBConnection.DriverName; public class Crud { static DB mongoConn = null; public static void Connect(DBConnection dbCon) {
if (dbCon.getDriverName() == DriverName.mongodb) {
ServerAddress serverAddress = new ServerAddress(dbCon.getServerHost(), Integer.valueOf(dbCon.getServerPort()));
List<ServerAddress> addrs = new ArrayList<>();
addrs.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential(dbCon.getUserName(), dbCon.getSource(), dbCon.getPassword().toCharArray());
List<MongoCredential> credentials = new ArrayList<>();
credentials.add(credential); // 通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs, credentials); @SuppressWarnings("deprecation")
DB con = mongoClient.getDB(dbCon.getDbName()); mongoConn = con;
}
} public static String OperateDB(String sql, Boolean hasColumnName) {
String result = "";
if (sql.toUpperCase().contains(").FIND(")) {
result = Query(sql, hasColumnName); }
else if(sql.toUpperCase().contains(").REMOVE("))
{
result=String.valueOf(Delete(sql));
}
else if(sql.toUpperCase().contains(").UPDATE("))
{
result=String.valueOf(Update(sql));
}
else {
result= String.valueOf(Create(sql));
}
return result;
} private static String Query(String sql, Boolean hasColumnName) {
String tableName = RegExpUtil.getTableName(sql);
String query = RegExpUtil.getQuery(sql);
List<String> columnNames = getColumnNames(query); BasicDBObject queryObject = (BasicDBObject) JSON.parse(query);
DBCursor cursor = mongoConn.getCollection(tableName).find(queryObject);
JSONArray lists = new JSONArray(); while (cursor.hasNext()) {
JSONObject jsonObj = new JSONObject();
JSONArray subLists = new JSONArray();
DBObject o = cursor.next();
if (!columnNames.isEmpty()) {
if(!hasColumnName)
{
for (String columnName : columnNames)
subLists.add(o.get(columnName));
lists.add(subLists);
}
else {
for (String columnName : columnNames)
jsonObj.put(columnName, o.get(columnName));
lists.add(jsonObj);
}
} else {
if(!hasColumnName)
{
Iterator<String> it = o.keySet().iterator();
while(it.hasNext())
subLists.add(o.get(it.next()));
lists.add(subLists);
}
else {
lists.add(o);
}
} }
return FastJsonUtil.ObjectToString(lists);
} private static int Create(String sql)
{
String tableName = RegExpUtil.getTableName(sql);
String create = RegExpUtil.getCreate(sql);
BasicDBObject createObject = (BasicDBObject) JSON.parse(create);
WriteResult writeResult = mongoConn.getCollection(tableName).save(createObject);
return writeResult.getN();
} private static int Update(String sql)
{
String tableName = RegExpUtil.getTableName(sql); String update = RegExpUtil.getUpdate(sql);
BasicDBObject updateQueryObject = (BasicDBObject) JSON.parse(update); String upset = getUpset(update);
BasicDBObject upsetObject = (BasicDBObject) JSON.parse(upset);
WriteResult updateResult = mongoConn.getCollection(tableName).update(updateQueryObject, upsetObject);
return updateResult.getN();
} private static int Delete(String sql)
{
String tableName = RegExpUtil.getTableName(sql);
String delete = RegExpUtil.getRemove(sql);
BasicDBObject deleteObject = (BasicDBObject) JSON.parse(delete);
WriteResult writeResult = mongoConn.getCollection(tableName).remove(deleteObject);
return writeResult.getN();
} private static List<String> getColumnNames(String query) {
String tmp = RegExpUtil.getObject(query,1);
return RegExpUtil.getColumnNames(tmp);
} private static String getUpset(String query) {
String tmp = RegExpUtil.getObject(query, 1);
return tmp;
}
}

3 实体类DBConnection.java

package com.mongodb.util;

public class DBConnection {
public enum DriverName {
oracle, db2, sqlserver, mysql, sybase, postgresql,mongodb
}
private String dbConnectionName;
private DriverName driverName;
private String serverHost;
private String serverPort;
private String source;
private String dbName;
private String userName;
private String password;
public String getDbConnectionName() {
return dbConnectionName;
}
public void setDbConnectionName(String dbConnectionName) {
this.dbConnectionName = dbConnectionName;
}
public DriverName getDriverName() {
return driverName;
}
public void setDriverName(DriverName driverName) {
this.driverName = driverName;
}
public String getServerHost() {
return serverHost;
}
public void setServerHost(String serverHost) {
this.serverHost = serverHost;
}
public String getServerPort() {
return serverPort;
}
public void setServerPort(String serverPort) {
this.serverPort = serverPort;
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
} }

4 RegExpUtil.java

package com.mongodb.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class RegExpUtil { static String tableRegExp = "getCollection\\('(\\w+?)'\\)";
static String queryRegExp = "\\.find\\((.*?)\\)";
static String columnNameRegExp = "'(\\w+?)':";
static String createRegExp = "\\.save\\((.*?)\\)";
static String removeRegExp = "\\.remove\\((.*?)\\)";
static String updateRegExp = "\\.update\\((.*?)\\)"; static public String getObject(String str, int index) {
int len = str.length();
char[] chars = str.toCharArray();
Stack<Character> stack = new Stack<Character>();
int begin = 0, end = 0, i = 0, curIndex = 0;
while (i < len && curIndex <= index) {
// '{'入栈
while (i < len&&stack.empty()) {
if (chars[i] == '{') {
stack.push(chars[i]);
begin = i;
}
++i;
}
if (stack.empty()) {
return "";
}
// 第curIndex个object
while (!stack.empty() && i < len) {
if (chars[i] == '{') {
stack.push(chars[i]); }
if (chars[i] == '}') {
if (!stack.empty() && stack.peek() == '{') {
stack.pop();
}
}
++i;
}
if (stack.empty()) {
end = i - 1;
if (curIndex == index)
return str.substring(begin, end+1);
} else {
return "";
} ++curIndex;
}
return "";
} public static List<String> getColumnNames(String sql) {
return GetWithRegExps(sql, columnNameRegExp);
} public static String getTableName(String sql) {
return GetWithRegExp(sql, tableRegExp);
} public static String getQuery(String sql) {
return GetWithRegExp(sql, queryRegExp);
} public static String getCreate(String sql) {
return GetWithRegExp(sql, createRegExp);
} public static String getUpdate(String sql) {
return GetWithRegExp(sql, updateRegExp);
} public static String getRemove(String sql) {
return GetWithRegExp(sql, removeRegExp);
} private static String GetWithRegExp(String s, String regExp) {
Pattern r = Pattern.compile(regExp);
// 现在创建 matcher 对象
Matcher m = r.matcher(s);
if (m.find()) {
return m.group(1);
} return "";
} private static List<String> GetWithRegExps(String s, String regExp) {
List<String> ss = new ArrayList<String>();
Pattern r = Pattern.compile(regExp);
// 现在创建 matcher 对象
Matcher m = r.matcher(s);
while (m.find()) {
ss.add(m.group(1));
} return ss;
} }

5 FastJsonUtil.java

package com.mongodb.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature; public class FastJsonUtil {
public static String ObjectToString(Object o) {
String s = JSON.toJSONString(o);
return TrimDoubleQuote(s);
} private static String TrimDoubleQuote(String s) {
if (s.startsWith("\"") && s.endsWith("\"")) {
s = s.substring(1, s.length());
s = s.substring(0, s.length() - 1);
}
return s;
}
}

待完善

代码暂不支持:

  • 正则表达式查询,如 db.getCollection('laAppInterface').find({'appCode':/^1.*?1$/})  中正则表达式 /^1.*?1$/
  • 不支持函数,如db.getCollection('laAppInterface').update({'interfaceId':'TEST-API-0000068'},{$set:{"invokeType":NumberInt(1)}}); 中函数NumberInt(1)

Java实现mongodb原生增删改查语句的更多相关文章

  1. Java连接MongoDB进行增删改查

    1.导入必须的包: 详情看项目:http://pan.baidu.com/s/1cvDAOY 2.通过Myeclipse创建WEB项目 3. 3.bean:创建实体类 package com.bean ...

  2. MongoDB常用增删改查语句

    数据库database 创建及查看库 1.有则使用这个数据库,没有就创建 use DATABASE_NAME 2. 查看当前选择的数据库,默认是test db 3.查看数据库,默认有admin.loc ...

  3. 2,MongoDB之增删改查及pymongo的使用

    本章我们来学习一下关于 MongoDB的增删改查 一.MongoDB操作 之 原生ORM,根本不存在SQL语句 创建数据库:这里和一般的关系型数据库一样,都要先建立一个自己的数据库空间 是的,Mong ...

  4. Java连接MySQL数据库增删改查通用方法

    版权声明:本文为博主原创文章,未经博主允许不得转载. Java连接MySQL数据库增删改查通用方法 运行环境:eclipse+MySQL 以前我们Java连接MySQL数据库都是一个数据库写一个类,类 ...

  5. Scala对MongoDB的增删改查操作

    =========================================== 原文链接: Scala对MongoDB的增删改查操作 转载请注明出处! ==================== ...

  6. python 全栈开发,Day124(MongoDB初识,增删改查操作,数据类型,$关键字以及$修改器,"$"的奇妙用法,Array Object 的特殊操作,选取跳过排序,客户端操作)

    一.MongoDB初识 什么是MongoDB MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介 ...

  7. SpringBoot操作MongoDB实现增删改查

    本篇博客主讲如何使用SpringBoot操作MongoDB. SpringBoot操作MongoDB实现增删改查 (1)pom.xml引入依赖 <dependency> <group ...

  8. MongoDB之增删改查(一)

    本文主要介绍MongoDB数据库增删改查操作. 增 mongoDB和其它关系型数据库一样,通过insert来添加数据到集合中去. db.collectionName.insert(内容) 显示数据库中 ...

  9. MongoDB的增删改查 转

    MongoDB的增删改查 (黎明你好原创作品,转载请注明) MongoDB中数据的基本单元叫做文档,采用json的键-值的方式.多个键及其关联的值有序的存放在一起变是文档.类似于编程语言中的键值关系. ...

随机推荐

  1. 框架学习笔记之Maven简介和配置

    一.什么是Maven?★Maven可翻译为“知识的积累”.“专家”.“内行”,它是一个跨平台的项目管理工具.★Maven提供了开发人员构建一个完整的生命周期框架,开发团队可以自动完成项目的基础工具建设 ...

  2. mysql5.7中解决中文乱码的问题

    在使用mysql5.7时,会发现通过web端向数据库中写入中文后会出现乱码,但是在数据库中直接操作SQL语句插入数据后中文就显示正常,这个问题怎么解决呢?此处不对mysql的数据编码过程和原理进行讲解 ...

  3. 注册表命令 regedit32

    转自 https://zhidao.baidu.com/question/1958216489744783460.html Regedt32.exe 不支持注册表项文件 (.reg) 的导入和导出. ...

  4. axios + mock.js模拟数据实现前后端分离开发的实例代码

    首先就是必须安装axios和mock.js npm install axios npm install mockjs 1. 然后在文档src中新建一个mock.js文件,如图 2. 在main.js中 ...

  5. hihoCoder 1015 KMP算法

    题意:经典字符串匹配算法.给定原串和模式串,求模式串在原串中出现的次数.算法讲解 AC代码 #include <cstdio> #include <cmath> #includ ...

  6. MyBatis入门一

    本人只是刚刚学习MyBatis,作为学习路程的记录,写的不好,不完善的地方请多多包涵: 首先,先比较一下Hibernate和MyBatis两种框架之间的区别: 两种都是ORM框架,但是Hibernat ...

  7. rpm检验是否被改动过

    参考原文http://vbird.dic.ksu.edu.tw/linux_basic/0520rpm_and_srpm.php#rpmmanager_verify   rpm -qVa   (当然可 ...

  8. md5加密用户登陆遇到的问题及解决办法

    有个项目的登陆模块使用到了cas,应需求要求,用户名和密码传输时使用了md5加密模式,加密的密码可以直接保存在数据库,但是加密的用户名则必须解密出来才行,于是后台的java代码中便写了针对用户名的解密 ...

  9. dojo表格分页之各个参数代表的意义(一)

    下面是dojo表格分页参数代表的意义 //每页可以显示10/15/20/25/30条记录 (1)pageSizes: [10, 15, 20, 25,30], //每页显示的记录从多少到多少,共多少条 ...

  10. zTree实现地市县三级级联DAO接口测试

    zTree实现地市县三级级联DAO接口测试 ProvinceDaoTest.java: /** * @Title:ProvinceDaoTest.java * @Package:com.gwtjs.d ...