因为业务原因新整合了 mongo 驱动3.0,使用mongoDB的高级查询。并编写了MongoDBUtil工具类。如图为驱动包的maven依赖。
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.2</version>
</dependency>
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
MongoDBUtil工具类
package com.xunxin.service.app.user;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.xunxin.vo.user.UserEntity;
/**
* Copyright © 2017 noseparte(Libra) © Like the wind, like rain
* @Author Noseparte
* @Compile 2017年11月29日 -- 下午4:22:47
* @Version 1.0
* @Description MongoDB 驱动3.0工具类
*/
public final class MongoDBUtil {
private static MongoClient mongoClient = null;
private static MongoDatabase database = null;
private static ServerAddress serverAddress = null;
private static MongoCredential credentials = null;
private static List<ServerAddress> addressLists = new ArrayList<ServerAddress>();
private static List<MongoCredential> credentialsLists = new ArrayList<MongoCredential>();
private static final String IP = "192.168.1.105";
private static final int PORT = 10001;
public static void init() {
try {
serverAddress = new ServerAddress(IP, PORT);
addressLists.add(serverAddress);
// credentials = MongoCredential.createMongoCRCredential("test1", "test",
// "test1".toCharArray());
// credentialsLists.add(credentials);
// mongoClient = new MongoClient(addressLists, credentialsLists);
mongoClient = new MongoClient(addressLists);
} catch (MongoException e) {
System.out.println(e.toString());
}
if (null != mongoClient) {
database = mongoClient.getDatabase("test");
}
}
public static MongoClient getMongoClient() {
if (null == mongoClient) {
init();
}
return mongoClient;
}
public static MongoClient getMongoClient() {
if (null == mongoClient) {
init();
}
return mongoClient;
}
/**
* 获取database
*
* @return
*/
public static MongoDatabase getDatabase() {
if (null == mongoClient) {
init();
}
return database;
}
/**
* 获取User Collection
*
* @return
*/
public static MongoCollection<Document> getUserCollection() {
if (null == database) {
database = getDatabase();
}
if (null != database) {
return database.getCollection("data");
}
return null;
}
/**
* 删除所有用户
*/
public static void deleteAllUsers() {
System.out.println("删除User Collection中所有数据...");
MongoCollection<Document> collection = getUserCollection();
FindIterable<Document> cursor = collection.find();
while (cursor.iterator().hasNext()) {
collection.deleteOne(cursor.iterator().next());
}
System.out.println("====================================");
}
/**
* 查询所有用户
*/
public static void queryAllUsers() {
System.out.println("查询User Collection中所有数据:");
MongoCollection<Document> collection = getUserCollection();
// 方法一
/*
* MongoCursor<Document> cur = collection.find().iterator(); try{ while
* (cur.hasNext()) { System.out.println(cur.next().toJson()); } }catch(Exception
* e){ System.out.println(e.getMessage()+e); }finally { cur.close(); }
*/
// 方法二
for (Document cursor : collection.find()) {
System.out.println(cursor.toJson());
}
System.out.println("================================================================");
}
/**
* 保存用户信息
*
* @param user
*/
public static void saveUser(UserEntity user) {
System.out.println("保存用户信息:" + user.toString());
MongoCollection<Document> userCollection = getUserCollection();
// userCollection.insertOne(user.toBasicDBObject());
System.out.println("================================================================");
}
/**
* 更新用户信息
*
* @param user
*/
// public static void update(User user) {
// System.out.println("更新用户信息:" + user.toString());
// MongoCollection<Document> userCollection = getUserCollection();
// userCollection.updateMany(new Document().append("name", user.getName()), user.toBasicDBObject());
// System.out.println("================================================================");
// }
/**
* 增加用户更新次数
*
* @param userName
* 用户名
*/
public static void incUserUpdateTimes(String userName) {
MongoCollection<Document> userCollection = getUserCollection();
BasicDBObject newDocument = new BasicDBObject().append("$inc", new BasicDBObject().append("updateTimes", 1));
userCollection.updateOne(new BasicDBObject().append("name", userName), newDocument);
}
/**
* 更新用户名
*
* @param oldName
* 旧用户名
* @param newName
* 新用户名
*/
public static void updateUserName(String oldName, String newName) {
MongoCollection<Document> userCollection = getUserCollection();
BasicDBObject newDocument = new BasicDBObject().append("$set", new BasicDBObject().append("name", newName));
userCollection.updateOne(new BasicDBObject().append("name", oldName), newDocument);
}
/**
* 更新User Age
*
* @param userName
* 用户名
* @param age
* Age
*/
public static void updateUserAge(String userName, int age) {
MongoCollection<Document> userCollection = getUserCollection();
BasicDBObject newDocument = new BasicDBObject().append("$set", new BasicDBObject().append("age", age));
userCollection.updateOne(new BasicDBObject().append("name", userName), newDocument);
}
public static void queryUserByGreatThanAge(int age) {
MongoCollection<Document> userCollection = getUserCollection();
BasicDBObject query = new BasicDBObject();
query.put("age", new BasicDBObject("$gt", age));
FindIterable<Document> cursor = userCollection.find(query);
while (cursor.iterator().hasNext()) {
System.out.println(cursor.iterator().next());
}
}
public static void queryUserByLessThanAge(int age) {
MongoCollection<Document> userCollection = getUserCollection();
BasicDBObject query = new BasicDBObject();
query.put("age", new BasicDBObject("$lt", age));
FindIterable<Document> cursor = userCollection.find(query);
while (cursor.iterator().hasNext()) {
System.out.println(cursor.iterator().next());
}
}
public static void queryUserNotEquireAge(int age) {
MongoCollection<Document> userCollection = getUserCollection();
BasicDBObject query = new BasicDBObject();
query.put("age", new BasicDBObject("$ne", age));
FindIterable<Document> cursor = userCollection.find(query);
while (cursor.iterator().hasNext()) {
System.out.println(cursor.iterator().next());
}
}
public static void deleteUserByName(String userName) {
MongoCollection<Document> userCollection = getUserCollection();
BasicDBObject document = new BasicDBObject();
document.put("name", userName);
userCollection.deleteMany(document);
}
public static void deleteUserByNameList(List<String> nameList) {
MongoCollection<Document> userCollection = getUserCollection();
BasicDBObject query = new BasicDBObject();
query.put("name", new BasicDBObject("$in", nameList));
userCollection.deleteMany(query);
}
public static void setDatabase(MongoDatabase database) {
MongoDBUtil.database = database;
}
启动项目时候出现如下错误:
java.lang.NoSuchFieldError: autoConnectRetry
刚开始mongo部分的service注入失败,误以为是jar包冲突。重新加载本地maven仓库,依然报如上错误。
仔细研究console的bug信息之后发现下面的错误信息:
Usage of 'mongo-options' is no longer supported for MongoDB Java driver version 3 and above. Please use 'mongo-client-options' and refer to chapter 'MongoDB 3.0 Support' for details
翻译过来就是说使用mongo 3.0驱动之后要将<mongo:mongo改成<mongo:mongo-client对应的<mongo:options改成<mongo:client-options,还没有结束。
接下来会接着报错 不允许出现属性:'auto-connect-retry'、'slave-ok' 之类的提示
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 33 in XML document from class path resource [application-config.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 33; columnNumber: 25; cvc-complex-type.3.2.2: 元素 'mongo:client-options' 中不允许出现属性 'auto-connect-retry'。
最终的代码,项目正常运行。
<mongo:mongo-client host="192.168.1.105" port="10001">
<mongo:client-options connections-per-host="10"
threads-allowed-to-block-for-connection-multiplier="5"
connect-timeout="10000"
socket-keep-alive="false" ></mongo:client-options>
</mongo:mongo-client>
共同学习,写下你的评论
评论加载中...
作者其他优质文章