Mongodb總結3-稍微封裝一下
上次發表的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"情況。
相關文章
- 稍微改一下 Wiki.js 的介面 CSSJSCSS
- ReactNative 之FlatList踩坑封裝總結React封裝
- 總結一下
- ES6封裝MongoDB的CRUD封裝MongoDB
- 對api請求封裝的探索和總結API封裝
- MongoDB查詢總結MongoDB
- MongoDB基礎總結MongoDB
- Golang 對MongoDB的操作簡單封裝GolangMongoDB封裝
- 用go封裝一下臨時tokenGo封裝
- MongoDB知識點總結MongoDB
- MongoDB的學習總結MongoDB
- MongoDB監控方法總結MongoDB
- mongoDB 小指令碼總結MongoDB指令碼
- Mongodb總結4-Spring環境使用MongodbMongoDBSpring
- 統一結果封裝封裝
- ES6(四)用Promise封裝一下IndexedDBPromise封裝Index
- 用go封裝一下二級認證功能Go封裝
- # 095 01 Android 零基礎入門 02 Java物件導向 02 Java封裝 01 封裝的實現 03 # 088 01 Android 零基礎入門 02 Java物件導向 02 Java封裝 03 封裝總結 01 封裝知識點總結AndroidJava物件封裝
- MongoDB shell常用命令總結MongoDB
- mongodb 階段性技術總結MongoDB
- MongoDB Python官方驅動 PyMongo 的簡單封裝MongoDBPython封裝
- Mongodb總結5-通過裝飾模式,用Mongodb解決Hbase的不穩定問題MongoDB模式
- 常用的MongoDB技術網站總結MongoDB網站
- MongoDB的分片資料庫命令總結MongoDB資料庫
- 總結一下所學的內容
- 工作總結ppt模板,瞭解一下!
- 總結一下最近遇到的問題
- 總結一下最近的Go學習Go
- 總結一些,規劃一下
- 最後一刻,總結一下
- 總結一下開啟新的航程
- .NET Core MongoDB資料倉儲和工作單元模式封裝MongoDB模式封裝
- vue-axios的總結及專案中的常見封裝方法。VueiOS封裝
- MongoDB管理使用者相關操作總結MongoDB
- 【封裝那些事】 缺失封裝封裝
- 總結一下本週遇到的問題
- 總結一下linux遠端控制方法Linux
- 簡單總結一下NotificationCenter、KVC、KVO、Delegate