javascript
Spring boot mongodb
mongodb語(yǔ)法
?
spring boot mongodb
引入
pom依賴(lài)
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency></dependencies>application配置
spring: mongodb:uri: mongodb://name:password@localhost:27017/test?
訪(fǎng)問(wèn)數(shù)據(jù)
MongoRepository
public interface PersonMongoDBRepository extends MongoRepository<Person,String> {Person findByName(String name);@Query("{'age':?0}")List<Person> withQueryFindByAge(Integer age);}@Service class AA { @Autowired PersonMongoDBRepository personMongoDBRepository ; }MongoRepository提供了通過(guò)id 操作文檔的能力。
MongoTemplate
@Autowiredpublic MongoTemplate mongoTemplate;MongoTemplate提供了自定義查詢(xún)的能力。
<T> List<T> find(Query query, Class<T> entityClass); <T> List<T> find(Query query, Class<T> entityClass, String collectionName);Query
1、org.springframework.data.mongodb.core.query
構(gòu)造函數(shù)
Query (Criteria criteria)
接受的參數(shù)是org.springframework.data.mongodb.core.query.Criteria
Criteria是標(biāo)準(zhǔn)查詢(xún)的接口,可以引用靜態(tài)的Criteria.where的把多個(gè)條件組合在一起,就可以輕松地將多個(gè)方法標(biāo)準(zhǔn)和查詢(xún)連接起來(lái),方便我們操作查詢(xún)語(yǔ)句
2、BasicQuery
子類(lèi) org.springframework.data.mongodb.core.query.BasicQuery 提供了更底層的查詢(xún)能力,即JSON格式的封裝。
BasicQuery(DBObject queryObject) BasicQuery(DBObject queryObject, DBObject fieldsObject) BasicQuery(java.lang.String query) BasicQuery(java.lang.String query, java.lang.String fields)?
3、Document
通過(guò)org.bson.Document直接操作BSON定義查詢(xún),需要自己進(jìn)行類(lèi)型轉(zhuǎn)換。
//自定義查詢(xún) ,JSON格式。Document filter = builderFilter(request.getFilter());if (filterExtension != null) {filter = filterExtension.apply(filter);}//獲取CollectionString collectionName = mongoTemplate.getCollectionName(AppData.class);MongoCollection collection = mongoTemplate.getCollection(collectionName);long count = collection.countDocuments(filter);FindIterable<Document> found = collection.find(filter);//設(shè)置排序Document sort = buildSort(request.getSort());found.sort(sort);//設(shè)置 projectionDocument projection = buildProjection(request);if (projection != null) {found.projection(projection);}if (request.getFrom() > 0) {found.skip(request.getFrom());}if (request.getSize() > 0) {found.limit(request.getSize());}List<AppData> list = new ArrayList<>();//進(jìn)行類(lèi)型轉(zhuǎn)換。使用MongoConverterfound.forEach((Block<? super Document>) e -> {AppData appData = mongoConverter.read(AppData.class, e);list.add(appData);});PagedResult<AppData> result = new PagedResult<>(count, list);Update
update可以更新數(shù)據(jù),修改某個(gè)屬性,可以是簡(jiǎn)單類(lèi)型,也可以是自定義類(lèi)型
//更新版本int newVersion = appData.getVersion() + 1;Update update = Update.update(AppData.PATH_VERSION, newVersion);//更新檢查狀態(tài)update.set(PATH_QUALITY,appData.getSMD().getQuality());mongoTemplate.updateMulti(query,update,AppData.class);?
實(shí)體
/*** 應(yīng)用數(shù)據(jù)日志*/ @Data @Document(collection = "AppDataLog") public class AppDataLog {@Idprivate ObjectId id;/*** 資源Id*/@Field("ResourceId")private String resourceId;/*** 版本*/@Field("Version")private int version;/*** 服務(wù)名稱(chēng)*/@Field("Service")private String service ="";/*** 是否已檢查*/@Field("Checked")private boolean checked;/*** 檢查時(shí)間*/@Field("CheckedTime")private Date checkedTime = null;/*** 檢查結(jié)果*/@Field("CheckedStatus")private int checkedStatus = 0;public QualityStatus getCheckedStatus(){return QualityStatus.valueOf(this.checkedStatus);}public void setCheckedStatus(QualityStatus status){this.checkedStatus = status.getValue();};}?
注解
spring-data-mongodb中的實(shí)體映射是通過(guò)MongoMappingConverter這個(gè)類(lèi)實(shí)現(xiàn)的。它可以通過(guò)注釋把java類(lèi)轉(zhuǎn)換為mongodb的文檔。
它有以下幾種注釋:
- @Id
?文檔的唯一標(biāo)識(shí),在mongodb中為ObjectId,它是唯一的,通過(guò)時(shí)間戳+機(jī)器標(biāo)識(shí)+進(jìn)程ID+自增計(jì)數(shù)器(確保同一秒內(nèi)產(chǎn)生的Id不會(huì)沖突)構(gòu)成。
- @Document
把一個(gè)java類(lèi)聲明為mongodb的文檔,可以通過(guò)collection參數(shù)指定這個(gè)類(lèi)對(duì)應(yīng)的文檔。
@DBRef 聲明類(lèi)似于關(guān)系數(shù)據(jù)庫(kù)的關(guān)聯(lián)關(guān)系。ps:暫不支持級(jí)聯(lián)的保存功能,當(dāng)你在本實(shí)例中修改了DERef對(duì)象里面的值時(shí),單獨(dú)保存本實(shí)例并不能保存DERef引用的對(duì)象,它要另外保存,如下面例子的Person和Account。
- @Field
代表一個(gè)字段,可以不加,不加的話(huà)默認(rèn)以參數(shù)名為列名。參數(shù)名為 定義的 Java類(lèi)字段的名稱(chēng),不是get**,set**等的標(biāo)準(zhǔn)屬性名。
例如:private int version //屬性對(duì)應(yīng)的mongodb名稱(chēng)為version,而不是Version。
- @Indexed?
聲明該字段需要索引,建索引可以大大的提高查詢(xún)效率。
- @CompoundIndex
復(fù)合索引的聲明,建復(fù)合索引可以有效地提高多字段的查詢(xún)效率。
- @GeoSpatialIndexed?
聲明該字段為地理信息的索引。
- @Transient??
映射忽略的字段,該字段不會(huì)保存到mongodb。
- @PersistenceConstructor?
聲明構(gòu)造函數(shù),作用是把從數(shù)據(jù)庫(kù)取出的數(shù)據(jù)實(shí)例化為對(duì)象。該構(gòu)造函數(shù)傳入的值為從DBObject中取出的數(shù)據(jù)。
問(wèn)題解決
去掉_class字段
方法:為MongoTypeMapper指定一個(gè)空的TypeMapper。
@BeanMappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context,MongoCustomConversions conversions) {DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);mappingConverter.setCustomConversions(conversions);mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null) );return mappingConverter;}枚舉Enum與int 的轉(zhuǎn)換
mongodb默認(rèn)不支持int與Enum的轉(zhuǎn)換,spring提供的converts包含了,但是mongodb在判斷時(shí)沒(méi)有使用。
自定義converter(不可用)
@Beanpublic MongoCustomConversions customConversions() {List<Converter<?,?>> converters = new ArrayList<Converter<?,?>>();converters.add( new IntegerToEnumConvert ());converters.add( new EnumToIntegerConvert());return new MongoCustomConversions(converters);}問(wèn)題:
1、IntegerToEnum 會(huì)覆蓋mongodb中的Int to Int,導(dǎo)致異常。
2、EnumToInt ,不會(huì)被使用,內(nèi)部會(huì)找到自帶的EnumToIntFactory,自定義的只會(huì)作為觸發(fā),讓代碼去找EnumToIntFactory,如果不加入,代碼不會(huì)去找?EnumToIntFactory 。
枚舉只作為訪(fǎng)問(wèn)方法結(jié)果和參數(shù)類(lèi)型:
public enum QualityStatus {//待檢查Pending(0,"待檢查"),//合法Available(1,"合法"),//異常Abnormal(2,"異常");private int value ;private String description;private QualityStatus (int value,String description){this.value = value;this.description = description;}public int getValue(){return value;}public String getDescription(){return description;}public static QualityStatus valueOf(int value){switch (value){case 0:return Pending;case 1:return Available;case 2:return Abnormal;default:throw new IllegalArgumentException(Integer.toString(value));}}}GridFSBucket 不存在
@Configuration public class MongodbConfig {@Autowiredprivate MongoDbFactory mongoDbFactory;@Beanpublic GridFSBucket getGridFSBucket(){MongoDatabase db = mongoDbFactory.getDb();return GridFSBuckets.create(db);} }去掉其他數(shù)據(jù)庫(kù)
springboot啟動(dòng)報(bào)錯(cuò):Failed to configure a DataSource: 'url' attribute is not specified and no embedded
如果有其他數(shù)據(jù)庫(kù),但是不使用,可以排除掉。
@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class) public class AssetsBizAppliction { }Projection
1、Projection cannot have a mix of inclusion and exclusion.
只有_id可以混合 包含與過(guò)濾
CodecConfigurationException
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class XXX;
??????? @Autowired
?????? MongoConverter mongoConverter;
?
????? //進(jìn)行類(lèi)型轉(zhuǎn)換。使用MongoConverter
??????? found.forEach((Block<? super Document>) e -> {
??????????? AppData appData = mongoConverter.read(AppData.class, e);
??????????? list.add(appData);
??????? });
總結(jié)
以上是生活随笔為你收集整理的Spring boot mongodb的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Spring @Conditional
- 下一篇: Spring @Import源码解析