1.前提准备
需要导入的jar包:
gson-2.7.jar
mongo-java-driver-3.4.2.jar
mongodb-driver-3.4.2.jar
mongodb-driver-core-3.4.2.jar
2.java连接MongoDB
自己整理的工具类
import java.util.ArrayList;
import java.util.List;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.snaillove.web.cloudmusic.common.modules.utils.Common;
public class MongoDBHelp {
// 获得Mongo配置文件
Common common = new Common();
// 初始化monogodb
private MongoClient client = null;
public MongoClient getConnection() {
// 配置连接
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
build.connectionsPerHost(50); // 与数据最大连接数50
// 如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
build.threadsAllowedToBlockForConnectionMultiplier(50);
build.connectTimeout(1 * 60 * 1000);
build.maxWaitTime(2 * 60 * 1000);
MongoClientOptions options = build.build();
// ip,端口
ServerAddress serverAddress1 = new ServerAddress(common.getMongoHost(), 27017);
List<ServerAddress> seeds = new ArrayList<ServerAddress>();
seeds.add(serverAddress1);
// 用户名,数据库名,密码
MongoCredential credentials = MongoCredential.createScramSha1Credential(common.getMongoUsername(),
common.getMongoDatabase(), common.getMongoPassword().toCharArray());
List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
credentialsList.add(credentials);
// 连接数据库
client = new MongoClient(seeds, credentialsList, options);
return client;
}
public void close() {
client.close();
}
}
3.Java对MongoDB的增删查改
public class VisitBannerDao {
MongoDBDao client = new MongoDBDao();
@SuppressWarnings("deprecation")
public List<VisitBanner> findList(VisitBanner visitBanner, PageModel pageModel) {
// 指定数据库名
DB db = client.getConnection().getDB("databaseName");
// 获取集合,不存在的话,会自动建立该集合(相当于关系数据库中的数据表)
DBCollection collection = db.getCollection("collectionName");
// 操作数据库
List<VisitBanner> list = new ArrayList<VisitBanner>();
try {
// 条件列表
BasicDBList condList = new BasicDBList();
// 临时条件对象
BasicDBObject cond = new BasicDBObject();
if (!StringUtils.isEmpty(visitBanner.getAppId())) {
cond.append("appId", visitBanner.getAppId());// 此处意味appId这个字段等于visitBanner.getAppId()这个值
condList.add(cond);
}
if (!StringUtils.isEmpty(visitBanner.getStartDate())) {
BasicDBObject startCondition = new BasicDBObject("$gte", visitBanner.getStartDate());
cond = new BasicDBObject("insertDate", startCondition);// 此处意味insertDate大于等于visitBanner.getStartDate()这个值
condList.add(cond);
}
if (!StringUtils.isEmpty(visitBanner.getEndDate())) {
BasicDBObject endCondition = new BasicDBObject("$lte", visitBanner.getEndDate());
cond = new BasicDBObject("insertDate", endCondition);
condList.add(cond);
}
// 整合条件查询
BasicDBObject searchCond = new BasicDBObject();
searchCond.put("$and", condList);// 将条件列表中的条件用and连接起来
DBCursor cursor = null;
BasicDBObject orderBy = new BasicDBObject("insertDate", -1);// 排序条件(1:ASC,-1:DESC)
if (condList.size() != 0) {
cursor = collection.find(searchCond).sort(orderBy);// 查询数据库
} else {
cursor = collection.find().sort(orderBy);
}
while (cursor.hasNext()) {// 将数据库中查询的cursor转换成对象
DBObject obj = cursor.next();
// 反转
Gson gson = new Gson();
VisitBanner entity = gson.fromJson(obj.toString(), VisitBanner.class);
list.add(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// MongoClient使用完后必须要close释放资源
client.close();
}
return list;
}
public void save(VisitBanner visitBanner) {
// 指定数据库名
DB db = client.getConnection().getDB("datebaseName");
// 获取集合,不存在的话,会自动建立该集合(相当于关系数据库中的数据表)
DBCollection collection = db.getCollection("collectionName");
// 操作数据库
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
visitBanner.setInsertDate(time);
Gson gson = new Gson();
// 转换成json字符串,再转换成DBObject对象
DBObject dbObject = (DBObject) JSON.parse(gson.toJson(visitBanner));
// 插入数据库
collection.insert(dbObject);
} catch (Exception e) {
e.printStackTrace();
} finally {
// MongoClient使用完后必须要close释放资源
client.close();
}
}
@Test
public void update() {
// 指定数据库名
DB db = client.getConnection().getDB("databaseName");
// 获取集合,不存在的话,会自动建立该集合(相当于关系数据库中的数据表)
DBCollection collection = db.getCollection("collectionName");
// 操作数据库
try {
VisitBanner oldbanner=new VisitBanner();
oldbanner.setBannerTitle("雨天");
VisitBanner newbanner=new VisitBanner();
newbanner.setBannerTitle("晴天");
Gson gson = new Gson();
// 转换成json字符串,再转换成DBObject对象
DBObject query = (DBObject) JSON.parse(gson.toJson(oldbanner));
DBObject update = (DBObject) JSON.parse(gson.toJson(newbanner));
// 插入数据库
collection.update(query, update);
} catch (Exception e) {
e.printStackTrace();
} finally {
// MongoClient使用完后必须要close释放资源
client.close();
}
}
@Test
public void delete() {
// 指定数据库名
DB db = client.getConnection().getDB("databaseName");
// 获取集合,不存在的话,会自动建立该集合(相当于关系数据库中的数据表)
DBCollection collection = db.getCollection("collectionName");
// 操作数据库
try {
VisitBanner visitBanner=new VisitBanner();
visitBanner.setBannerTitle("雨天");
Gson gson = new Gson();
// 转换成json字符串,再转换成DBObject对象
DBObject dbObject = (DBObject) JSON.parse(gson.toJson(visitBanner));
// 插入数据库
collection.remove(dbObject);
} catch (Exception e) {
e.printStackTrace();
} finally {
// MongoClient使用完后必须要close释放资源
client.close();
}
}
}