springboot使用mongodb
這是一篇關于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:
????????????(用于增刪改查,這里只用到了查詢和插入方法)
????????(4) MongoUtil
????? ? 用于mongoClient 客戶端的連接
(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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《Java并发编程实践-第一部分》-读书
- 下一篇: 进阶篇-安卓系统:2.多点触控的交互处理