上次发表的2,纯粹是Demo,演示API的用法。

今天,稍微封装了下,看得更清楚。

考虑到不容易做得很有通用性,所以封装的一般,换种场景需要直接修改代码,但是有一部分是可以复用的。

最近项目,很可能只需要4个接口,增加、修改、单个查询、批量查询,所以只封装了4个接口的用法。

package mongodb;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List; import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo; public class MongoDBDemoAdvance { public static final String TITLE = "title";
public static final String CONTENT = "content";
public static final String AUTHOR = "author";
public static final String DATE = "date";
public static final String ID = "id"; //构造1个文章、修改之后再存、2个查询
public static void main(String[] args) { Mongo mongo = MongoUtil.mongo();
DB db = mongo.getDB("blog"); Article article = buildArticle();
DBCollection articleCollection = add(db, article); article.setId(2L);
DBObject object2 = articleToObject2(article);
articleCollection.insert(object2); Long id = 1L;
Article articleBefore = findById(articleCollection, id);
if (articleBefore != null) {
System.out.println("刚刚新增的文章=" + articleBefore);
} articleBefore.setTitle("标题被修改啦");
update(articleCollection, articleBefore);
Article articleAfter = findById(articleCollection, id);
if (articleAfter != null) {
System.out.println("修改后的文章=" + articleAfter);
} List idList = Arrays.asList(1L, 2L);
List<Article> articleList = findByIdList(articleCollection, idList);
if (articleList != null) {
for (Article a : articleList) {
System.out.println(a);
}
} BasicDBObject removeAll = new BasicDBObject();
articleCollection.remove(removeAll);
} //增加
public static DBCollection add(DB db, Article article) {
DBObject object = articleToObject2(article);
DBCollection articleCollection = db.getCollection("article");
articleCollection.insert(object);
return articleCollection;
} //构造测试数据
private static Article buildArticle() {
Article article = new Article();
article.setAuthor("FansUnion");
article.setContent("neirong");
article.setDate(new Date());
article.setId(1L);
article.setTitle("title");
return article;
} // 从集合中,根据ID查找
public static Article findById(DBCollection collection, Long id) {
BasicDBObject searchArticleById = new BasicDBObject();
searchArticleById.append(ID, id);
Article articleBefore = null;
DBCursor cursor = collection.find(searchArticleById);
while (cursor.hasNext()) {
DBObject articleObject = cursor.next();
articleBefore = objectToArticle(articleObject); String internalId = articleObject.get("_id").toString();
articleBefore.setInternalId(internalId);
}
cursor.close();
return articleBefore;
} // 修改
public static void update(DBCollection collection, Article article) {
if (article.getId() == null) {
return;
} BasicDBObject updateCondition = new BasicDBObject();
updateCondition.append(ID, article.getId()); DBObject newObject = BeanUtil.bean2DBObject(article); DBObject updateSetValue = new BasicDBObject("$set", newObject);
collection.update(updateCondition, updateSetValue);
} //根据ID集合查找
public static List<Article> findByIdList(DBCollection collection,
List<Long> idList) {
BasicDBList values = new BasicDBList();
values.addAll(idList); DBObject inQuery = new BasicDBObject("$in", values); DBObject con = new BasicDBObject();
con.put(ID, inQuery);
DBCursor cursorIdArray = collection.find(con); List<Article> articleList = new ArrayList<Article>();
while (cursorIdArray.hasNext()) {
DBObject articleObject = cursorIdArray.next();
Article article = new Article();
BeanUtil.dbObject2Bean(articleObject, article);
String internalId = articleObject.get("_id").toString();
article.setInternalId(internalId); articleList.add(article);
}
return articleList;
} //对象转换
private static Article objectToArticle(DBObject object) {
if (object == null) {
return null;
}
Article article = new Article();
// 用工具方法转换,手动转换,需要判断类型,比较麻烦
article = BeanUtil.dbObject2Bean(object, article);
return article;
} // 手动把Bean转换为Mongodb的对象
private static BasicDBObject articleToObject(Article article) {
BasicDBObject object = new BasicDBObject();
object.append(TITLE, article.getTitle());
object.append(CONTENT, article.getContent());
object.append(AUTHOR, article.getAuthor());
object.append(DATE, article.getDate());
object.append(ID, article.getId());
return object;
} // 实用工具转换,简单
private static DBObject articleToObject2(Article article) {
return BeanUtil.bean2DBObject(article);
}
}

和上一篇总结2的区别

1.文章先用Java对象表示。

public class Article {
private Long id;
private String title;
private String content;
private String author;
private Date date;

}

2.Mongodb的参数用个配置类。

public class MongodbConfig {

private String host;
private String port;
private String db;

}

3.Mongodb获得连接,用个类表示。

public class MongoUtil {
public static final int DEFAULT_PORT = 27017;
public static final String DEFAULT_HOST = "172.17.100.150"; private static Mongo instance; @Resource(name="mongodbConfig")
private static MongodbConfig mongodbConfig; public static Mongo mongo() {
try {
if (instance == null) {
instance = new Mongo(DEFAULT_HOST, DEFAULT_PORT);
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return instance;
} public static void close() {
if (instance != null) {
instance.close();
}
} }

4.Bean工具类,把Java对象和Mongodb对象进行转换。

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date; import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.ArrayUtils; import com.mongodb.BasicDBObject;
import com.mongodb.DBObject; public class BeanUtil { /**
* 把实体bean对象转换成DBObject
*/
public static <T> DBObject bean2DBObject(T bean)
{
if (bean == null) {
return null;
}
DBObject dbObject = new BasicDBObject();
// 获取对象对应类中的所有属性域
Field[] fields = bean.getClass().getDeclaredFields();
//父类的属性
Field[] parentFields=bean.getClass().getSuperclass().getDeclaredFields();
//合并
Field[] allFeilds=(Field[]) ArrayUtils.addAll(fields, parentFields);
for (Field field : allFeilds) {
// 获取属性名
String varName = field.getName();
// 修改访问控制权限
boolean accessFlag = field.isAccessible();
if (!accessFlag) {
field.setAccessible(true);
}
Object param;
try {
param = field.get(bean);
if (param == null) {
continue;
} else if (param instanceof Integer) {// 判断变量的类型
int value = ((Integer) param).intValue();
dbObject.put(varName, value);
} else if (param instanceof String) {
String value = (String) param;
dbObject.put(varName, value);
} else if (param instanceof Double) {
double value = ((Double) param).doubleValue();
dbObject.put(varName, value);
} else if (param instanceof Float) {
float value = ((Float) param).floatValue();
dbObject.put(varName, value);
} else if (param instanceof Long) {
long value = ((Long) param).longValue();
dbObject.put(varName, value);
} else if (param instanceof Boolean) {
boolean value = ((Boolean) param).booleanValue();
dbObject.put(varName, value);
} else if (param instanceof Date) {
Date value = (Date) param;
dbObject.put(varName, value);
}
// 恢复访问控制权限
field.setAccessible(accessFlag);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
} }
return dbObject;
} /**
* 把DBObject转换成bean对象
*/
public static <T> T dbObject2Bean(DBObject dbObject, T bean) {
if (bean == null) {
return null;
}
Field[] fields = bean.getClass().getDeclaredFields();
Field[] parentFields=bean.getClass().getSuperclass().getDeclaredFields();
Field[] allFeilds=(Field[]) ArrayUtils.addAll(fields, parentFields);
for (Field field : allFeilds) {
String varName = field.getName();
Object object = dbObject.get(varName);
if (object != null) {
try {
BeanUtils.setProperty(bean, varName, object);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
return bean;
}
}

5.方法封装的,看起来更清晰。

add、findById、update、findByIdList。

上次的demo**,主要是演示。

6.特别说明,BeanUtil中把Mongodb对象和Java对象互相转换的时候,要考虑到简单的继承"extends"情况。

Mongodb总结3-稍微封装一下的更多相关文章

  1. 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

    适用于app.config与web.config的ConfigUtil读写工具类   之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...

  2. MongoDB学习笔记~自己封装的Curd操作(查询集合对象属性,更新集合对象)

    回到目录 我不得不说,mongodb官方驱动在与.net结合上做的不是很好,不是很理想,所以,我决定对它进行了二次封装,这是显得很必然了,每个人都希望使用简单的对象,而对使用复杂,麻烦,容易出错的对象 ...

  3. 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)

    近期工作中有使用到 MongoDb作为日志持久化对象,需要实现对MongoDb的增.删.改.查,但由于MongoDb的版本比较新,是2.4以上版本的,网上已有的一些MongoDb Helper类都是基 ...

  4. mongodb 的基本函数语法封装

    //这个模块里面封装了所有对数据库的常用操作 var MongoClient = require('mongodb').MongoClient; var config = require(" ...

  5. Golang 对MongoDB的操作简单封装

    使用MongoDB的Go驱动库 mgo,对MongoDB的操作做一下简单封装 初始化 操作没有用户权限的MongoDB var globalS *mgo.Session func init() { s ...

  6. Mongodb for .Net Core 封装类库

    一:引用的mongodb驱动文件版本为 Mongodb.Driver 20.4.3 二:我只是进行了常用方法的封装,如有不当之处,请联系我 创建mongodb的连接 using MongoDB.Bso ...

  7. golang mongodb 驱动二次封装

    mongodb 官方的go驱动包 go.mongodb.org/mongo-driver 使用起来比较繁琐,最近对其进行了二次封装 github地址:https://github.com/w3liu/ ...

  8. MongoDB学习笔记~自己封装的Curd操作(按需更新的先决条件)

    回到目录 我们上一讲中介绍了大叔封装的Mongo仓储,其中介绍了几个不错的curd操作,而对于按需更新内部子对象,它是有条件的,即你的子对象不能为null,也就是说,我们在建立主对象时,应该为子对象赋 ...

  9. 【MongoDB:】稍微复杂的操作

    1:插入数据稍微复杂的形式 doc=( {"user_id" : "ABCDBWN", "password" :"ABCDBWN& ...

  10. MongoDB Helper的简单封装

    db.properties #mongodb数据库配置文件 #数据库server所在的ip地址 ip=127.0.0.1  #mongodb服务port号 port=27017 #要连接的库 dbNa ...

随机推荐

  1. Flex 编译器及编译步骤

    通过为Flex项目添加编译器参数:-keep-generated-actionscript=true 可以看到经过编译器处理过的源程序文件集合. 在这些文件的文件名中包含有“xxx-generated ...

  2. 关于props default 数组/对象的默认值应当由一个工厂函数返回

    export default {props: { xAxisData: {   type: Array,   default: [] }, },这是我的代码 报错是Invalid default va ...

  3. 昼猫笔记 JavaScript -- 面向对象(I)

    本文内容搬运自公众号 原文链接 本文主要内容:面向对象 预计阅读时间:6分钟 面向对象的方式 单例模式(字面量定义) var obj = {} 类的实例 var obj = new Object() ...

  4. 【Henu ACM Round#17 D】Hexagons!

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 题目的图吓人. 找下规律就会发现从内到外是1,6,12,18 即1,16,26,36... 即1+6(1+2+3+...) 等差求和 ...

  5. Ubuntu中的解压缩文件的方式

    记录Ubuntu下各种压缩和解压方式: .tar 解包:tar xvf FileName.tar 打包:tar cvf FileName.tar DirName (注:tar是打包,不是压缩!) -- ...

  6. javap 命令 反编译代码

    javap 命令 javap -c classname 一个好的分析class二进制文件的 链接 http://blog.csdn.net/pwlazy/article/details/7954169

  7. JavaScript--数据结构与算法之散列

    散列:实现散列表的数据后可以快速地实现插入或者删除.但是对于实现查找操作则效率非常的低.散列表的底层是数组实现的,长度是预先设定,可以随时根据需求增加.所有的元素根据和该元素对应的键,保存在特定的位置 ...

  8. HTML 页面内容禁止选中

    写一个小笔记,怎么禁止HTML页面不被选中,复制. CSS: *{ moz-user-select: -moz-none; -moz-user-select: none; -o-user-select ...

  9. golang语言入门及安装

    golang语言入门及安装 go语言是google在2009年发布的开源编程语言使用Go编译的程序可以媲美C或C++代码的速度,而且更加安全.支持并行进程. 本次讲解在windows上安装go语言的开 ...

  10. Linux "零拷贝" sendfile函数中文说明及实际操作分析

    Sendfile函数说明 #include ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count); sendfile ...