一、基本的增删改查:
1、pom:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wtyy</groupId>
<artifactId>mongodbdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
</project>
2、application.properties配置文件:
server.port = 8080
server.context-path = /wechat
3、连接util:这里可以连接多个服务,以逗号分隔,如:
String adressList = "localhost:27017,xxx.xxx.xx:port";
package com.wtyy.util;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
/**
* mongodb管理器,提供DB对象。
*/
public class MongodbManager {
private static final Logger LOGGER = LoggerFactory.getLogger("mongodbManager");
private static MongoClient client;
private static String dbnameTL = "wechatdb";
static {
String adressList = "localhost:27017";
try {
String[] addresses = adressList.split(",");
ArrayList<ServerAddress> serverAddressList = new ArrayList<ServerAddress>();
for(int j=0; j < addresses.length; j++){
String[] address = addresses[j].split(":");
ServerAddress mongoAddress = new ServerAddress(address[0], Integer.parseInt(address[1]));
serverAddressList.add(mongoAddress);
}
client = new MongoClient(serverAddressList);
client.setReadPreference(ReadPreference.primaryPreferred());
LOGGER.info("读写分离未启动");
client.setWriteConcern(WriteConcern.SAFE);
LOGGER.info("写入安全模式启动");
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
public static final DB DB_TL = client.getDB(dbnameTL);
}
4、dto:
package com.wtyy.dto;
import java.io.Serializable;
public class WechatGroup implements Serializable{
/**
*
*/
private static final long serialVersionUID = 3439169789270606886L;
private String groupId;
private String groupName;
@Override
public String toString() {
return "WechatGroup [groupId=" + groupId + ", groupName=" + groupName
+ "]";
}
}
5、dao:
package com.wtyy.dao;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.springframework.stereotype.Repository;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.wtyy.dto.WechatGroup;
import com.wtyy.util.MongodbManager;
@Repository("wechatDao")
public class WechatDao {
private String collection = "wechat";
//添加群
public void addGroup(WechatGroup wechatGroup){
DBCollection dbCollection = MongodbManager.DB_TL.getCollection(collection);
DBObject documents = new BasicDBObject();
documents.put("groupId", wechatGroup.getGroupId());
documents.put("groupName", wechatGroup.getGroupName());
dbCollection.insert(documents );
}
//通过群名称获取群id
public String getWechatGroupIdByName(String wechatGroupName){
String name = null;
try{
DBCollection dbCollection = MongodbManager.DB_TL.getCollection(collection);
BasicDBObject cond = new BasicDBObject();
cond.put("groupName", wechatGroupName);
DBCursor dbCursor = dbCollection.find(cond);
while(dbCursor.hasNext()){
Map map = (Map)dbCursor.next();
return (String) map.get("groupId");
}
return name;
}catch (Exception e) {
// TODO: handle exception
}
return name;
}
/**
* 查询所有
*/
public List<WechatGroup> getAll() {
List<WechatGroup> list = new ArrayList<>();
try{
DBCollection dbCollection = MongodbManager.DB_TL.getCollection(collection);
BasicDBObject cond = new BasicDBObject();
DBCursor dbCursor = dbCollection.find(cond);
while(dbCursor.hasNext()){
Map map = (Map)dbCursor.next();
WechatGroup wechatGroup = new WechatGroup();
wechatGroup.setGroupId((String) map.get("groupId"));
wechatGroup.setGroupName((String) map.get("groupName"));
list.add(wechatGroup);
}
return list;
}catch (Exception e) {
// TODO: handle exception
}
return list;
}
/**
* 修改
*/
public void updateNameById(WechatGroup wechatGroup){
List<WechatGroup> list = new ArrayList<>();
try{
DBCollection dbCollection = MongodbManager.DB_TL.getCollection(collection);
//查询条件
BasicDBObject query = new BasicDBObject();
query.put("groupId", wechatGroup.getGroupId());
BasicDBObject updateObj = new BasicDBObject();
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("groupName", wechatGroup.getGroupName());
updateObj.put("$set", newDocument);
dbCollection.update(query, updateObj);
}catch (Exception e) {
// TODO: handle exception
}
}
/**
* 删除
*/
public void deleteById(String groupId){
try{
DBCollection dbCollection = MongodbManager.DB_TL.getCollection(collection);
//查询条件
BasicDBObject query = new BasicDBObject();
query.put("groupId", groupId);
dbCollection.remove(query);
}catch (Exception e) {
// TODO: handle exception
}
}
}
6、测试:
package com.wtyy.test;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wtyy.dao.WechatDao;
import com.wtyy.dto.WechatGroup;
@RestController
@RequestMapping("/test")
public class Test {
@Autowired
private WechatDao wechatDao;
@RequestMapping("/add")
public void add(String groupId,String groupName){
WechatGroup group = new WechatGroup();
group.setGroupId(groupId);
group.setGroupName(groupName);
wechatDao.addGroup(group);
}
@RequestMapping("/get")
public String get(String groupName){
return wechatDao.getWechatGroupIdByName(groupName);
}
@RequestMapping("/getAll")
public List<WechatGroup> getAll(){
return wechatDao.getAll();
}
@RequestMapping("/update")
public void update(WechatGroup wechatGroup ){
wechatDao.updateNameById(wechatGroup);
}
@RequestMapping("/delete")
public void delete( String groupId){
wechatDao.deleteById(groupId);
}
}
二、