前言:这是之前4篇的汇总
Java操作MongoDB主要有两种方式:
1.MongoTemplate
2.MongoCollection
根据实际情况,我选用的MongoCollection,后面也会补充MongoTemplate的用法
业务代码(利用API做了分页查询)
package net.pushi.neo4jdata.dataParser.service.impl;
import com.mongodb.ConnectionString;
import com.mongodb.client.*;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import net.pushi.neo4jdata.dataParser.service.MongoDBService;
import net.pushi.neo4jdata.util.MongoDBUtil;
import org.bson.Document;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class MongoDBServiceImpl implements MongoDBService{
@Value("${spring.data.mongodb.uri}")
private String uri;
@Value("${spring.data.mongodb.db}")
private String db;
//连接MongoDB
public MongoDatabase createConnect(){
MongoClient mongoClient = MongoClients.create(new ConnectionString(uri));
MongoDatabase database = mongoClient.getDatabase(db);
return database;
}
//连接指定MongoDB库
public MongoCollection<Document> getDBCollection(String collectionName) {
Map<String, MongoCollection<Document>> dbCollectionMap = new ConcurrentHashMap<String, MongoCollection<Document>>();
MongoCollection<Document> collection = null;
if (dbCollectionMap.containsKey(collectionName)) {
collection = dbCollectionMap.get(collectionName);
} else {
collection = createConnect().getCollection(collectionName);
if (null != collection) {
dbCollectionMap.put(collectionName, collection);
}
}
return collection;
}
//新增
@Override
public Map insertManyByCollectionName(Map<String, Object> map) {
List<Map<String, Object>> list = new ArrayList<>();
List<Document> documents = new ArrayList<>();
if (map.get("insert")instanceof List){
list = (List<Map<String, Object>>) map.get("insert");
for (int i=0;i<list.size();i++){
Document document = new Document();
for (Map.Entry<String, Object> entry : list.get(i).entrySet()){
document.put(entry.getKey(),entry.getValue());
}
documents.add(document);
}
}
getDBCollection(map.get("collectionName").toString()).insertMany(documents);
int sum = list.size();
return new HashMap<String, Object>(){{put("code","200");put("message","新增数"+ sum);}};
}
//删除
@Override
public Map deleteManyByCollectionName(Map<String, Object> map) {
//筛选条件
Map<String,Object> filter = new HashMap<>();
if (map.get("filter")instanceof Map){
filter = (Map<String, Object>) map.get("filter");
}
DeleteResult deleteResult = getDBCollection(map.get("collectionName").toString()).deleteMany(MongoDBUtil.setParameter(filter));
return new HashMap<String, Object>(){{put("code","200");put("message","删除数"+deleteResult.getDeletedCount());}};
}
//更新
@Override
public Map updateManyByCollectionName(Map<String, Object> map) {
//筛选条件
Map<String,Object> filter = new HashMap<>();
if (map.get("filter")instanceof Map){
filter = (Map<String, Object>)map.get("filter");
}
//需改内容
Map<String,Object> set = new HashMap<>();
if (map.get("set")instanceof Map){
set = (Map<String, Object>) map.get("set");
}
Document document = new Document("$set", new Document(MongoDBUtil.setParameter(set)));
//执行修改
UpdateResult updateResult = getDBCollection(map.get("collectionName").toString()).updateMany(MongoDBUtil.setParameter(filter), document);
return new HashMap<String, Object>(){{put("code","200");put("message","匹配数"+updateResult.getMatchedCount()+";修改数"+updateResult.getModifiedCount());}};
}
//查询
@Override
public Map findAllByCollectionName(Map<String, Object> map) {
Map<String, Object> mapList = new HashMap<>();
List<Map<String,Object>> list = new ArrayList<>();
Map<String,Object> filter = new HashMap<>();
if (map.get("filter")instanceof Map){
filter = (Map<String, Object>)map.get("filter");
}
//分页查询
int pageNumber = 1;
int pageSize = 0;
if (map.containsKey("pageNumber") && map.get("pageNumber")instanceof Integer){
pageNumber = (int) map.get("pageNumber");
}
if (map.containsKey("pageSize") && map.get("pageSize")instanceof Integer){
pageSize = (int) map.get("pageSize");
}
MongoCursor<Document> cursor = getDBCollection(map.get("collectionName").toString()).find(MongoDBUtil.setParameter(filter)).skip((pageNumber-1)*pageSize).limit(pageSize).iterator();
while (cursor.hasNext()){
Document document = cursor.next();
list.add(document);
}
cursor.close();
mapList.put("list",list);
return mapList;
}
}
工具类(包含了MongoTemplate的用法)
package net.pushi.neo4jdata.util;
import com.mongodb.BasicDBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* @ClassName MongoDBUtil
* @Desc TODO MongoDB 工具类
* @Date 2020/3/10 9:43
* @Version 1.0
*/
@Component
public class MongoDBUtil {
@Autowired
private static MongoTemplate mongoTemplate;
//参数处理
public static BasicDBObject setParameter(Map<String, Object> map){
BasicDBObject query = new BasicDBObject();
query.putAll(map);
return query;
}
/*
* @ClassName MongoDBUtil
* @Desc TODO 创建集合,并返回是否创建成功 -2:已存在 / -1:创建失败 / 1:创建成功
* @Date 2020/3/10 10:59
* @Version 1.0
*/
public static Integer createCollection(String collectionName){
// 先判断集合是否存在
if(mongoTemplate.collectionExists(collectionName)){
return -2;
}else{
// 创建一个集合
mongoTemplate.createCollection(collectionName);
// 判断集合是否存在
if(mongoTemplate.collectionExists(collectionName)){
return 1;
}else{
return -1;
}
}
}
/*
* @ClassName MongoDBUtil
* @Desc TODO 在指定集合中添加数据
* @Date 2020/3/10 11:12
* @Version 1.0
*/
public static void add(Collection<?> batchToSave , String collectionName){
mongoTemplate.insert(batchToSave,collectionName);
}
/*
* @ClassName MongoDBUtil
* @Desc TODO 根据条件和指定集合删除数据
* @Date 2020/3/10 14:20
* @Version 1.0
*/
public static void delete(Query query , Object obj , String collectionName){
mongoTemplate.remove(query, obj.getClass(), collectionName);
}
/*
* @ClassName MongoDBUtil
* @Desc TODO 根据条件更新数据
* @Date 2020/3/10 14:30
* @Version 1.0
*/
public static void update(Query query , Update update , Object obj , String collectionName){
mongoTemplate.updateMulti(query , update , obj.getClass() , collectionName);
}
/*
* @ClassName MongoDBUtil
* @Desc TODO 获取指定集合下的全部数据
* @Date 2020/3/10 11:18
* @Version 1.0
*/
public static List<?> getAllByCollectionName(Object obj , String collectionName){
return mongoTemplate.findAll(obj.getClass(),collectionName);
}
/*
* @ClassName MongoDBUtil
* @Desc TODO 根据条件和集合名称查询数据
* @Date 2020/3/10 11:31
* @Version 1.0
*/
public static List<?> getByConditionAndCollectionName(Query query , Object obj , String collectionName){
return mongoTemplate.find(query, obj.getClass() , collectionName);
}
}
补充自定义分页:
1.通过实现Pageable接口,自定义
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import javax.validation.constraints.Min;
@NoArgsConstructor
@AllArgsConstructor
public class SpringDataPageAble implements Pageable {
@Min(1)
private Integer pageNumber = 1;
@Min(1)
private Integer pageSize = 10;
private Sort sort;
public void setSort(Sort sort) {
this.sort = sort;
}
// 当前页面
@Override
public int getPageNumber() {
return this.pageNumber;
}
// 每一页显示的条数
@Override
public int getPageSize() {
return getPagesize();
}
// 第二页所需要增加的数量
@Override
public long getOffset() {
return (getPageNumber() - 1) * getPagesize();
}
@Override
public Sort getSort() {
return sort;
}
public void setPagenumber(Integer pagenumber) {
this.pageNumber = pageNumber;
}
public Integer getPagesize() {
return this.pageSize;
}
public void setPagesize(Integer pagesize) {
this.pageSize = pagesize;
}
@Override
public Pageable next() {
return null;
}
@Override
public Pageable previousOrFirst() {
return null;
}
@Override
public Pageable first() {
return null;
}
@Override
public boolean hasPrevious() {
return false;
}
}
2.在repository层定义分页方法
import com.tedu.huawei.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserFirstRepository extends MongoRepository<User,String> {
Page<User> getUserByAgeGreaterThan(int age, Pageable pageAble);
}
3.service层调用方法
public Page<User> getUserByAgeGraterThan(int age, int pageNumber,int pageSize){
SpringDataPageAble springDataPageAble = new SpringDataPageAble(pageNumber,pageSize,new Sort(Sort.Direction.ASC,"age"));
return firstRepository.getUserByAgeGreaterThan(age,springDataPageAble);
}
将每次新的尝试记录下来,聚沙成塔
积跬步,至千里