大家好,我是烤鸭:

这是一篇关于springboot项目中使用mongodb。

环境:

jdk 1.8

springboot 1.5.6.RELEASE

maven 3.5

1. mongodb在springboot中的配置

springboot集成这个三方插件就是简单,只需要引入依赖,在properties或者yml中

添加相应的参数配置就好了。

(1)  引入依赖

以maven为例:

其中mongodb两个依赖包:

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId><version>1.5.6.RELEASE</version></dependency><dependency><groupId>org.mongodb</groupId><artifactId>mongodb-driver</artifactId><version>3.4.2</version></dependency>

(2)properties或者yml配置(我这次没用到这个配置,是在工具类代码中直接写的)

以yml为例:

spring:data:mongodb:host: 127.0.0.1port: 27017username: musicpassword: musicdatabase: music

这里几个参数就是:

IP地址,端口号,用户名,密码,数据库。

2.   mongodb的使用

(1)创建想存到mongo中的实体映射类,继承Document类

我这里是想存一些歌曲。

MusicInfo.java:

package com.test.test.test.bean;import org.bson.BsonDocument;
import org.bson.BsonDocumentWrapper;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.types.ObjectId;import java.io.Serializable;/*** Created by */
public class MusicInfo extends Document implements Serializable {private Integer returnId;private Integer id;private String mid;private String desc;private String name;private String singerName;private String fileHash;private String hqHash;private String albumId;private String type;   //平台标识private String keyword; //查询关键字/*** 无参构造=*/public MusicInfo() {super();}/*** 全参构造,添加到Map中*/public MusicInfo(Integer returnId, Long id, String mid, String desc, String name, String singerName, String fileHash, String hqHash, String albumId, String type) {super();this.append("returnId", returnId).append("id", id).append("mid", mid).append("desc", desc).append("name", name).append("singerName", singerName).append("fileHash", fileHash).append("albumId", albumId).append("type", type).append("keyword",keyword);}public MusicInfo(String keyword) {super();this.append("keyword", keyword);}/*** 该方法用于collection的update*/public void setUpdate(MusicInfo musicInfo) {this.append("$set", musicInfo);}/*** mongo 中的_id** @return*/public ObjectId get_Id() {return this.getObjectId("_id");}public void set_Id(ObjectId id) {this.append("_id", id);}public Integer getReturnId() {//return returnId;return this.getInteger("returnId");}public void setReturnId(Integer returnId) {//this.returnId = returnId;this.append("returnId", returnId);}public Integer getId() {Integer integer = this.getInteger("id");return integer;//return id;}public void setId(Integer id) {//this.id = id;this.append("id", id);}public String getMid() {return this.getString("mid");//return mid;}public void setMid(String mid) {//this.mid = mid;this.append("mid", mid);}public String getDesc() {return this.getString("desc");// return desc;}public void setDesc(String desc) {//this.desc = desc;this.append("desc", desc);}public String getName() {return this.getString("name");// return name;}public void setName(String name) {this.append("name", name);// this.name = name;}public String getSingerName() {return this.getString("singerName");// return singerName;}public void setSingerName(String singerName) {this.append("singerName", singerName);//this.singerName = singerName;}public String getFileHash() {return this.getString("fileHash");//return fileHash;}public void setFileHash(String fileHash) {this.append("fileHash", fileHash);// this.fileHash = fileHash;}public String getHqHash() {return this.getString("hqHash");//return hqHash;}public void setHqHash(String hqHash) {this.append("hqHash", hqHash);// this.hqHash = hqHash;}public String getAlbumId() {return this.getString("albumId");//return albumId;}public void setAlbumId(String albumId) {this.append("albumId", albumId);// this.albumId = albumId;}public String getType() {return this.getString("type");//return albumId;}public void setType(String type) {this.append("type", type);// this.albumId = albumId;}public String getKeyword() {return this.getString("keyword");//return albumId;}public void setKeyword(String keyword) {this.append("keyword", keyword);// this.albumId = albumId;}public <TDocument> BsonDocument toBsonDocument(Class<TDocument> documentClass, CodecRegistry codecRegistry) {// TODO Auto-generated method stubreturn new BsonDocumentWrapper<MusicInfo>(this, codecRegistry.get(MusicInfo.class));}@Overridepublic String toString() {return "MusicInfo[" +"_id='" + this.get_Id() + '\'' +"albumId='" + this.getAlbumId() + '\'' +", returnId=" + this.getReturnId() +", id=" + this.getId() +", mid='" + this.getMid() + '\'' +", desc='" + this.getDesc() + '\'' +", name='" + this.getName() + '\'' +", singerName='" + this.getSingerName() + '\'' +", fileHash='" + this.getFileHash() + '\'' +", hqHash='" + this.getHqHash() + '\'' +", type='" + this.getType() + '\'' +']';}
}   

(2)  创建歌曲对应操作mongodb的注册类

实现  CollectibleCodec接口

MusicInfoCodec.java:

package com.test.test.test.bean;import org.bson.*;
import org.bson.assertions.Assertions;
import org.bson.codecs.*;
import org.bson.codecs.configuration.CodecRegistry;import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;import static java.util.Arrays.asList;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;/*** Created by .***/
public class MusicInfoCodec implements CollectibleCodec<MusicInfo> {private static final String ID_FIELD_NAME = "_id";private static final CodecRegistry DEFAULT_REGISTRY = fromProviders(asList(new ValueCodecProvider(),new BsonValueCodecProvider(),new DocumentCodecProvider()));private static final BsonTypeClassMap DEFAULT_BSON_TYPE_CLASS_MAP = new BsonTypeClassMap();private final CodecRegistry registry;private final BsonTypeClassMap bsonTypeClassMap;private final IdGenerator idGenerator;private final Transformer valueTransformer;public MusicInfoCodec() {this(DEFAULT_REGISTRY, DEFAULT_BSON_TYPE_CLASS_MAP);}public MusicInfoCodec(final CodecRegistry registry, final BsonTypeClassMap bsonTypeClassMap) {this(registry, bsonTypeClassMap, null);}public MusicInfoCodec(final CodecRegistry registry, final BsonTypeClassMap bsonTypeClassMap, final Transformer valueTransformer) {this.registry = Assertions.notNull("registry", registry);this.bsonTypeClassMap = Assertions.notNull("bsonTypeClassMap", bsonTypeClassMap);this.idGenerator = Assertions.notNull("idGenerator", new ObjectIdGenerator());this.valueTransformer = valueTransformer != null ? valueTransformer : new Transformer() {@Overridepublic Object transform(final Object value) {return value;}};}@Overridepublic boolean documentHasId(final MusicInfo document) {return document.containsKey(ID_FIELD_NAME);}@Overridepublic BsonValue getDocumentId(final MusicInfo document) {if (!documentHasId(document)) {throw new IllegalStateException("The document does not contain an _id");}Object id = document.get(ID_FIELD_NAME);if (id instanceof BsonValue) {return (BsonValue) id;}BsonDocument idHoldingDocument = new BsonDocument();BsonWriter writer = new BsonDocumentWriter(idHoldingDocument);writer.writeStartDocument();writer.writeName(ID_FIELD_NAME);writeValue(writer, EncoderContext.builder().build(), id);writer.writeEndDocument();return idHoldingDocument.get(ID_FIELD_NAME);}@Overridepublic MusicInfo generateIdIfAbsentFromDocument(final MusicInfo document) {if (!documentHasId(document)) {document.put(ID_FIELD_NAME, idGenerator.generate());}return document;}@Overridepublic void encode(final BsonWriter writer, final MusicInfo document, final EncoderContext encoderContext) {writeMap(writer, document, encoderContext);}@Overridepublic MusicInfo decode(final BsonReader reader, final DecoderContext decoderContext) {MusicInfo document = new MusicInfo();reader.readStartDocument();while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {String fieldName = reader.readName();document.put(fieldName, readValue(reader, decoderContext));}reader.readEndDocument();return document;}@Overridepublic Class<MusicInfo> getEncoderClass() {return MusicInfo.class;}private void beforeFields(final BsonWriter bsonWriter, final EncoderContext encoderContext, final Map<String, Object> document) {if (encoderContext.isEncodingCollectibleDocument() && document.containsKey(ID_FIELD_NAME)) {bsonWriter.writeName(ID_FIELD_NAME);writeValue(bsonWriter, encoderContext, document.get(ID_FIELD_NAME));}}private boolean skipField(final EncoderContext encoderContext, final String key) {return encoderContext.isEncodingCollectibleDocument() && key.equals(ID_FIELD_NAME);}@SuppressWarnings({"unchecked", "rawtypes"})private void writeValue(final BsonWriter writer, final EncoderContext encoderContext, final Object value) {if (value == null) {writer.writeNull();} else if (Iterable.class.isAssignableFrom(value.getClass())) {writeIterable(writer, (Iterable<Object>) value, encoderContext.getChildContext());} else if (Map.class.isAssignableFrom(value.getClass())) {writeMap(writer, (Map<String, Object>) value, encoderContext.getChildContext());} else {Codec codec = registry.get(value.getClass());encoderContext.encodeWithChildContext(codec, writer, value);}}private void writeMap(final BsonWriter writer, final Map<String, Object> map, final EncoderContext encoderContext) {writer.writeStartDocument();beforeFields(writer, encoderContext, map);for (final Map.Entry<String, Object> entry : map.entrySet()) {if (skipField(encoderContext, entry.getKey())) {continue;}writer.writeName(entry.getKey());writeValue(writer, encoderContext, entry.getValue());}writer.writeEndDocument();}private void writeIterable(final BsonWriter writer, final Iterable<Object> list, final EncoderContext encoderContext) {writer.writeStartArray();for (final Object value : list) {writeValue(writer, encoderContext, value);}writer.writeEndArray();}private Object readValue(final BsonReader reader, final DecoderContext decoderContext) {BsonType bsonType = reader.getCurrentBsonType();if (bsonType == BsonType.NULL) {reader.readNull();return null;} else if (bsonType == BsonType.ARRAY) {return readList(reader, decoderContext);} else if (bsonType == BsonType.BINARY) {byte bsonSubType = reader.peekBinarySubType();if (bsonSubType == BsonBinarySubType.UUID_STANDARD.getValue() || bsonSubType == BsonBinarySubType.UUID_LEGACY.getValue()) {return registry.get(UUID.class).decode(reader, decoderContext);}}return valueTransformer.transform(registry.get(bsonTypeClassMap.get(bsonType)).decode(reader, decoderContext));}private List<Object> readList(final BsonReader reader, final DecoderContext decoderContext) {reader.readStartArray();List<Object> list = new ArrayList<Object>();while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {list.add(readValue(reader, decoderContext));}reader.readEndArray();return list;}}

(3)  MongoService:

(用于增删改查,这里只用到了查询和插入方法)

/*** Created by */
@Service
public class MongoService {/*** 数据插入MongoDB(初版)* @param Codec 用户将bson转化为Object的类* @param musicInfos 需要存储的实体集合* @param dbName 选择的db*///insertMongo(KeyEnum.TYPE_XIAMI.getKey(),keyword,resultContent);public  void insertMongo(CollectibleCodec Codec,List<MusicInfo> musicInfos,String dbName){String colName = "songlist";MongoUtil instance = MongoUtil.instance;CodecRegistry registry  = CodecRegistries.fromCodecs(Codec);MongoDatabase database = MongoUtil.instance.getDB(dbName);if(instance.getCollection(dbName, colName) ==null ){instance.createCollection(dbName, colName);}MongoCollection<MusicInfo> music = database.withCodecRegistry(registry).getCollection(colName, MusicInfo.class);musicInfos.forEach(item->{MusicInfo first = music.find(item, MusicInfo.class).first();if(null != first){return;}music.insertOne(item);});}public MongoService() {}/**** @param Codec 用户将bson转化为Object的类* @param musicInfo 封装查询条件的实体* @param dbName 选择的db* @return List<MusicInfo>*/public List<MusicInfo> getSongFromMongo(CollectibleCodec Codec,MusicInfo musicInfo,String dbName){String colName = "songlist";MongoUtil instance = MongoUtil.instance;CodecRegistry registry  = CodecRegistries.fromCodecs(Codec);MongoDatabase database = MongoUtil.instance.getDB(dbName);if(instance.getCollection(dbName, colName) ==null ){instance.createCollection(dbName, colName);}MongoCollection<MusicInfo> music = database.withCodecRegistry(registry).getCollection(colName, MusicInfo.class);ArrayList<MusicInfo> musicInfos = new ArrayList<>();Block<MusicInfo> block = new Block<MusicInfo>() {public void apply(MusicInfo t) {musicInfos.add(t);}};music.find(musicInfo,MusicInfo.class).forEach(block);return musicInfos;}public static void main(String[] args) {//查询
//        List<MusicInfo> musicInfoMongos = new MongoService().getSongFromMongo(new MusicInfoCodec(), new MusicInfo("小幸运"), "music";
//        for (int i = 0; i < musicInfoMongos.size(); i++) {
//            MusicInfo musicInfo =  musicInfoMongos.get(i);
//            System.out.println("mongo__"+musicInfo.getName());
//        }}
}

(4) MongoUtil

用于mongoClient 客户端的连接

package com.test.test.test.utils;import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.WriteConcern;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.ascending;
/*** Created by .*/
public enum MongoUtil {/*** 定义一个枚举的元素,它代表此类的一个实例*/instance;private static MongoClient mongoClient;static {System.out.println("===============MongoDBUtil初始化========================");String ip = "127.0.0.1";int port =27017;instance.mongoClient = new MongoClient(ip, port);// 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:// boolean auth = db.authenticate(myUserName, myPassword);Builder options = new MongoClientOptions.Builder();options.cursorFinalizerEnabled(true);// options.autoConnectRetry(true);// 自动重连true// options.maxAutoConnectRetryTime(10); // the maximum auto connect retry timeoptions.connectionsPerHost(300);// 连接池设置为300个连接,默认为100options.connectTimeout(30000);// 连接超时,推荐>3000毫秒options.maxWaitTime(5000); //options.socketTimeout(0);// 套接字超时时间,0无限制options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。options.writeConcern(WriteConcern.SAFE);//options.build();}// ------------------------------------共用方法---------------------------------------------------/*** 获取DB实例 - 指定DB** @param dbName* @return*/public MongoDatabase getDB(String dbName) {if (dbName != null && !"".equals(dbName)) {MongoDatabase database = mongoClient.getDatabase(dbName);return database;}return null;}//mongoDatabase.createCollection("test");public void createCollection(String dbName, String collName){try{mongoClient.getDatabase(dbName).createCollection(collName);}catch(Exception e){System.err.println(e.getClass().getName() + ": " + e.getMessage() );}}/*** 获取collection对象 - 指定Collection** @param collName* @return*/public MongoCollection<Document> getCollection(String dbName, String collName) {if (null == collName || "".equals(collName)) {return null;}if (null == dbName || "".equals(dbName)) {return null;}MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);return collection;}/*** 查询DB下的所有表名*/public List<String> getAllCollections(String dbName) {MongoIterable<String> colls = getDB(dbName).listCollectionNames();List<String> _list = new ArrayList<String>();for (String s : colls) {_list.add(s);}return _list;}/*** 获取所有数据库名称列表** @return*/public MongoIterable<String> getAllDBNames() {MongoIterable<String> s = mongoClient.listDatabaseNames();return s;}/*** 删除一个数据库*/public void dropDB(String dbName) {getDB(dbName).drop();}/*** 查找对象 - 根据主键_id** @param collection* @param id* @return*/public Document findById(MongoCollection<Document> collection, String id) {Document myDoc = collection.find(Filters.eq("_id", id)).first();return myDoc;}/** 统计数 */public int getCount(MongoCollection<Document> coll) {int count = (int) coll.count();return count;}/** 条件查询 */public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {return coll.find(filter).iterator();}/** 分页查询 */public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) {Bson orderBy = new BasicDBObject("_id", 1);return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();}/*** 通过ID删除** @param coll* @param id* @return*/public int deleteById(MongoCollection<Document> coll, String id) {int count = 0;ObjectId _id = null;try {_id = new ObjectId(id);} catch (Exception e) {return 0;}Bson filter = Filters.eq("_id", _id);DeleteResult deleteResult = coll.deleteOne(filter);count = (int) deleteResult.getDeletedCount();return count;}/*** FIXME** @param coll* @param id* @param newdoc* @return*/public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) {ObjectId _idobj = null;try {_idobj = new ObjectId(id);} catch (Exception e) {return null;}Bson filter = Filters.eq("_id", _idobj);// coll.replaceOne(filter, newdoc); // 完全替代coll.updateOne(filter, new Document("$set", newdoc));return newdoc;}public void dropCollection(String dbName, String collName) {getDB(dbName).getCollection(collName).drop();}/*** 关闭Mongodb*/public void close() {if (mongoClient != null) {mongoClient.close();mongoClient = null;}}/*** 测试入口** @param args* @throws CloneNotSupportedException*/public static void main(String[] args) {String dbName = "music";String collName = "songlist";MongoCollection<Document> coll = MongoUtil.instance.getCollection(dbName, collName);ListIndexesIterable<Document> list = coll.listIndexes();//查询所有索引for (Document document : list) {System.out.println("---"+document.toJson());}}}

(5) MongoService的使用:

@Autowired
private MongoService mongoService;public void insertMongo(){List<MusicInfo> musicInfos = new ArrayList<>();mongoService.insertMongo(new MusicInfoCodec(),monicInfos, "music");
}

上一张成功的图:

最后安利一个mongodb的PC图形化客户端:

Robo 3T

Robo 3T官网

springboot使用mongodb相关推荐

  1. Windows下安装Mongodb SpringBoot集成MongoDB和Redis多数据源

    全文内容: Mongodb安装 说明:Mongodb和redis是开发中常用的中间件,Redis的安装使用比较简单就不写了,只说本地也就是Windows安装Mongodb. SpringBoot集成M ...

  2. Springboot中mongodb的使用

    mongodb是最早热门非关系数据库的之一,使用也比较普遍,一般会用做离线数据分析来使用,放到内网的居多.由于很多公司使用了云服务,服务器默认都开放了外网地址,导致前一阵子大批 MongoDB 因配置 ...

  3. SpringBoot操作MongoDB实现增删改查

    本篇博客主讲如何使用SpringBoot操作MongoDB. SpringBoot操作MongoDB实现增删改查 (1)pom.xml引入依赖 <dependency> <group ...

  4. 直接裂开!京东二面被问SpringBoot整合MongoDB,我不会啊

    开始进入正题 一.技术介绍 SpringBoot整合MongoDB的实现步骤 一.技术介绍 1.MongoDB是什么? 二.使用步骤 1.MongoDB是什么? MongoDB(来自于英文单词&quo ...

  5. SpringBoot集成MongoDB

    SpringBoot集成MongoDB Pom依赖 <dependency><groupId>org.springframework.boot</groupId>& ...

  6. springboot中mongodb自定义类型转换器

    文章目录 1 场景 1.1 BigDecimal写入mongo 1.2 人工转换 1.3 自定义转换器 2 版本 3 步骤 3.1 定义转换器 3.2 配置mongoDb工厂类 3.3 加载自定义转换 ...

  7. core 实例化接口_实例讲解Springboot整合MongoDB进行CRUD操作的两种方式

    1 简介 Springboot是最简单的使用Spring的方式,而MongoDB是最流行的NoSQL数据库.两者在分布式.微服务架构中使用率极高,本文将用实例介绍如何在Springboot中整合Mon ...

  8. springboot集成mongoDB 异常认证

    springboot集成mongoDB 异常认证 参考文章: (1)springboot集成mongoDB 异常认证 (2)https://www.cnblogs.com/mh-study/p/980 ...

  9. SpringBoot使用MongoDB异常问题

    SpringBoot使用MongoDB异常问题 参考文章: (1)SpringBoot使用MongoDB异常问题 (2)https://www.cnblogs.com/linzhanfly/p/967 ...

  10. SpringBoot与MongoDB的集成使用

    wshanshi:来自喵桑的叹息,周末马上过去了-还是睡不醒的状态- 一.MongoDB简介 1.1.什么是MongoDB? MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据 ...

最新文章

  1. 小学毕业,努力5年,月入3万的程序员和他们的公众号!
  2. zookeeper伪分布式集群搭建
  3. windows常见的运行命令以及各快捷键组合
  4. Android仿网易新闻导航栏PagerSlidingTabStrip
  5. 重磅!『2021科技研究前沿』发布,重点关注11大领域、171个热点和新兴前沿!...
  6. aapr密码读取工具_wifi密码查看器原理是什么 wifi密码查看器原理介绍【详解】...
  7. 图片上添加文字--div
  8. 你需要知道的、有用的 Python 功能和特点
  9. matlab电机系统建模与仿真软件下载,同步电机模型的MATLAB仿真的设计(最终版)...
  10. 非科班转码,上岸小公司我也很满意了
  11. Windows10 64位安装MySQL(免安装版本)
  12. lecture9-提高模型泛化能力的方法
  13. Java将String型字符串转换成int型(或int型数组)
  14. python中out函数_Python中函数的使用
  15. Qt与Mysql进行连接实现账号的注册登录和密码修改和验证码
  16. Edge浏览器在新标签页打开链接(操作方法)
  17. 【洛谷】【模拟+栈】P4711 「化学」相对分子质量
  18. h5前端开发培训,html5学习笔记
  19. 计算机命令提示符开热点,win7系统使用cmd命令创建wifi热点的方法
  20. Windows10 2004五月更新正式版官方ISO纯净版镜像下载

热门文章

  1. 前端学习(3000):vue+element今日头条管理--远程仓库的issue
  2. [html] label都有哪些作用?并举相应的例子说明
  3. [vue] 说说你对slot的理解有多少?slot使用场景有哪些?
  4. [css] 要是position跟display、overflow、float这些特性相互叠加后会怎么样?
  5. [css] 用css怎么实现两端对齐?
  6. 前端学习(2570):template和jsx的对比
  7. “约见”面试官系列之常见面试题之第九十九篇之router和route(建议收藏)
  8. 前端学习(2334):angular之内置属性指令ngclass
  9. 前端学习(2003)vue之电商管理系统电商系统之之允许三级选择
  10. mybatis学习(19):模糊查询#