MongoDB:SpringBoot有关@Document(collection = )与@Document(collation= )注解的区别

 

目录

 

QUESTION:SpringBoot有关@Document(collection = "")与@Document(collation= "")注解的区别?

ANSWER:

一、问题原因

二、分析

2.1 Collection

@Id

@Document

@Indexed

@CompoundIndex

@Field

@Transient

@DBRef

2.2 Collation

2.2.1特性

2.2.2示例

转载博客出处:

 


 

 

QUESTION:SpringBoot有关@Document(collection = "")与@Document(collation= "")注解的区别?

 

ANSWER:

在启动项目时,报出如下异常:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'messageDaoImpl': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDbFactoryDependentConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 2 (BadValue): 'failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: "status", ns: "testdb.message", collation: { locale: "message" } } :: caused by :: Field 'locale' is invalid in: { locale: "message" }' on server www.youngxy.top:27018. The full response is {"ok": 0.0, "errmsg": "failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: \"status\", ns: \"testdb.message\", collation: { locale: \"message\" } } :: caused by :: Field 'locale' is invalid in: { locale: \"message\" }", "code": 2, "codeName": "BadValue"}; nested exception is com.mongodb.MongoCommandException: Command failed with error 2 (BadValue): 'failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: "status", ns: "testdb.message", collation: { locale: "message" } } :: caused by :: Field 'locale' is invalid in: { locale: "message" }' on server www.youngxy.top:27018. The full response is {"ok": 0.0, "errmsg": "failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: \"status\", ns: \"testdb.message\", collation: { locale: \"message\" } } :: caused by :: Field 'locale' is invalid in: { locale: \"message\" }", "code": 2, "codeName": "BadValue"}at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:126) [spring-boot-test-2.2.4.RELEASE.jar:2.2.4.RELEASE]at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) [spring-test-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) [spring-test-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123) [spring-test-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) [spring-test-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) [spring-test-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244) [spring-test-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98) [spring-test-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:337) [junit-jupiter-engine-5.5.2.jar:5.5.2]at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:342) [junit-jupiter-engine-5.5.2.jar:5.5.2]at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:337) [junit-jupiter-engine-5.5.2.jar:5.5.2]at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_202]at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_202]at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) ~[na:1.8.0_202]at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_202]at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_202]at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312) ~[na:1.8.0_202]at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743) ~[na:1.8.0_202]at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742) ~[na:1.8.0_202]at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580) ~[na:1.8.0_202]at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:336) [junit-jupiter-engine-5.5.2.jar:5.5.2]at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:259) [junit-jupiter-engine-5.5.2.jar:5.5.2]at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:252) [junit-jupiter-engine-5.5.2.jar:5.5.2]at java.util.Optional.orElseGet(Optional.java:267) ~[na:1.8.0_202]at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:251) [junit-jupiter-engine-5.5.2.jar:5.5.2]at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:29) ~[junit-jupiter-engine-5.5.2.jar:5.5.2]at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106) ~[junit-jupiter-engine-5.5.2.jar:5.5.2]at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105) ~[junit-jupiter-engine-5.5.2.jar:5.5.2]at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69) ~[junit-jupiter-engine-5.5.2.jar:5.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:107) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:107) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:75) ~[junit-platform-engine-1.5.2.jar:1.5.2]at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_202]at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80) ~[junit-platform-engine-1.5.2.jar:1.5.2]at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_202]at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51) ~[junit-platform-engine-1.5.2.jar:1.5.2]at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229) ~[junit-platform-launcher-1.5.2.jar:1.5.2]at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197) ~[junit-platform-launcher-1.5.2.jar:1.5.2]at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211) ~[junit-platform-launcher-1.5.2.jar:1.5.2]at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191) ~[junit-platform-launcher-1.5.2.jar:1.5.2]at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128) ~[junit-platform-launcher-1.5.2.jar:1.5.2]at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69) ~[junit5-rt.jar:na]at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) ~[junit-rt.jar:na]at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230) ~[junit-rt.jar:na]at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58) ~[junit-rt.jar:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDbFactoryDependentConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 2 (BadValue): 'failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: "status", ns: "testdb.message", collation: { locale: "message" } } :: caused by :: Field 'locale' is invalid in: { locale: "message" }' on server www.youngxy.top:27018. The full response is {"ok": 0.0, "errmsg": "failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: \"status\", ns: \"testdb.message\", collation: { locale: \"message\" } } :: caused by :: Field 'locale' is invalid in: { locale: \"message\" }", "code": 2, "codeName": "BadValue"}; nested exception is com.mongodb.MongoCommandException: Command failed with error 2 (BadValue): 'failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: "status", ns: "testdb.message", collation: { locale: "message" } } :: caused by :: Field 'locale' is invalid in: { locale: "message" }' on server www.youngxy.top:27018. The full response is {"ok": 0.0, "errmsg": "failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: \"status\", ns: \"testdb.message\", collation: { locale: \"message\" } } :: caused by :: Field 'locale' is invalid in: { locale: \"message\" }", "code": 2, "codeName": "BadValue"}at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]... 81 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 2 (BadValue): 'failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: "status", ns: "testdb.message", collation: { locale: "message" } } :: caused by :: Field 'locale' is invalid in: { locale: "message" }' on server www.youngxy.top:27018. The full response is {"ok": 0.0, "errmsg": "failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: \"status\", ns: \"testdb.message\", collation: { locale: \"message\" } } :: caused by :: Field 'locale' is invalid in: { locale: \"message\" }", "code": 2, "codeName": "BadValue"}; nested exception is com.mongodb.MongoCommandException: Command failed with error 2 (BadValue): 'failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: "status", ns: "testdb.message", collation: { locale: "message" } } :: caused by :: Field 'locale' is invalid in: { locale: "message" }' on server www.youngxy.top:27018. The full response is {"ok": 0.0, "errmsg": "failed to add collation information to index spec for index creation: { v: 2, key: { status: 1 }, name: \"status\", ns: \"testdb.message\", collation: { locale: \"message\" } } :: caused by :: Field 'locale' is invalid in: { locale: \"message\" }", "code": 2, "codeName": "BadValue"}

一、问题原因

经查找,'failed to add collation information to index spec for index creation:是指出了异常的问题。

在一个实体类中使用了:

@Document(collation = "message")

这里应该变为:

@Document(collection = "message")

二、分析

这里区分一下两者的区别:

2.1 Collection

 

@Id


主键,不可重复,自带索引,可以在定义的列名上标注,需要自己生成并维护不重复的约束。如果自己不设置@Id主键,mongo会自动生成一个唯一主键,并且插入时效率远高于自己设置主键。原因可参考上一篇mongo和mysql的性能对比。 
在实际业务中不建议自己设置主键,应交给mongo自己生成,自己可以设置一个业务id,如int型字段,用自己设置的业务id来维护相关联的表。

@Document


标注在实体类上,类似于hibernate的entity注解,标明由mongo来维护该表。

org.springframework.data.mongodb.core.mapping.Document.class
把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
@Document(collection="mongodb 对应 collection 名")      

// 若未加 @Document ,该 bean save 到 mongo 的 user collection
// 若添加 @Document ,则 save 到 reUser collection

org.springframework.data.mongodb.core.mapping.Document.class
把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
@Document(collection="mongodb 对应 collection 名")      // 若未加 @Document ,该 bean save 到 mongo 的 user collection
// 若添加 @Document ,则 save 到 reUser collection
@Document(collection="reUser") 
public class User{
}


@Indexed


声明该字段需要加索引,加索引后以该字段为条件检索将大大提高速度。 
唯一索引的话是@Indexed(unique = true)。 
也可以对数组进行索引,如果被索引的列是数组时,MongoDB会索引这个数组中的每一个元素。 
也可以对整个Document进行索引,排序是预定义的按插入BSON数据的先后升序排列。 
也可以对关联的对象的字段进行索引,譬如User对关联的address.city进行索引。(注解怎么写还不清楚,待查)

@CompoundIndex


复合索引,加复合索引后通过复合索引字段查询将大大提高速度。

@Document
@CompoundIndexes({@CompoundIndex(name = "age_idx", def = "{'lastName': 1, 'age': -1}")
})
public class Person<T extends Address> {
}


写法如上,lastName和age将作为复合索引,数字参数指定索引的方向,1为正序,-1为倒序。方向对单键索引和随机存不要紧,但如果你要执行分组和排序操作的时候,它就非常重要了。

@Field


代表一个字段,可以不加,不加的话默认以参数名为列名。

给映射存储到 mongodb 的字段取别名
在 java bean 中字段名为 firstName,存储到 mongo 中 key 为 fName
   

给映射存储到 mongodb 的字段取别名
在 java bean 中字段名为 firstName,存储到 mongo 中 key 为 fName@Field("fName")private String firstName; 


@Transient


被该注解标注的,将不会被录入到数据库中。只作为普通的javaBean属性。

@DBRef

 


关联另一个document对象。类似于mysql的表关联,但并不一样,mongo不会做级联的操作。 
先来看一下不加DBRef时,mongo保存数据的情况: 
Article类有String title,List pictureList,两个属性,Picture有一个url,一个desc属性。新建数个Picture对象,并赋值给Article的list,执行Article的insert操作,mongo保存的结果如图: 


 
list会作为普通的数据存到article里,并不会为Picture建表,这一点是区别于mysql的级联存储的。

在Article里给list加上DBRef注解后就不同了 


 
再次执行添加Article操作后,看结果 


 
发现就不再是直接显示的Picture的各个属性了,而是只保存了Picture的id和namespace,同时仍然没有创建Picture的collection(等同于mysql的表)。 
如此此时查询该Article,会发现list为空,并没有关联上Picture的值。其实上一步已经发现了,系统并没有去创建Picture的表。那即便Article关联了PictureList的id,也是无法查询的。 


官方解释: 
The mapping framework does not handle cascading saves. If you change an Account object that is referenced by a Person object, you must save the Account object separately. Calling save on the Person object will not automatically save the Account objects in the property accounts.意思就是不会处理级联保存,你必须单独处理关联的对象。 
现在修改一下添加Article的代码,先做Picture的持久化操作。 


 
再看结果,发现Picture已经被持久化,再次查询该Article时,相应的Picture也全部查了出来。 
如果在Article里删除关联的list,set为null并保存,系统只会删掉Article里关联的list,而Picture对象本身的数据是不会被删除的。 
从上面看来,貌似DBRef比较鸡肋,而且甚至有时还会带着误导的性质,譬如Article关联了两个空的Picture时在Article还能看到2个对象的引用,然后2个对象并不存在,是查询不出来的。 
那么这个标签存在的意义何在?

官方的说法是: 
In short,the best time to use DBRefs are when you’re storing heterogeneous references to documents in different collections.like when you want to take advantage of some additional DBRef-specific 
functionality in a driver or tool. 

实际使用中,感觉貌似作用是在不同的表做划分吧,有点模拟mysql外键的意思。免得数据都落到一个大表的,不便于做关联的表的查询。

 

 

2.2 Collation

 

2.2.1特性

Collation的3.4版本新特性。
拼写允许用户在字符串比较中使用特殊语言-特殊规则,例如字母拼写和口音标记规则。
你可以为一个收藏或视图、索引或支持拼写的具体操作做特色拼写。
一份拼写文件有以下字段:

{locale: <string>,caseLevel: <boolean>,caseFirst: <string>,strength: <int>,numericOrdering: <boolean>,alternate: <string>,maxVariable: <string>,backwards: <boolean>
}

 

当具体的拼写时,当地的拼写是强制性的;所有其他拼写是可选的。点击查看官方文档:see collation document.

2.2.2示例

db.createCollection("person")
db.person.insert({name: "张三"})
db.person.insert({name: "李四"})
db.person.insert({name: "王五"})
db.person.insert({name: "马六"})
db.person.insert({name: "张七"})

默认情况下,名字字段会被当做一个普通的二机制字符串来对比,按照name字段排序的结果如下

mongo-9554:PRIMARY&gt; db.person.find().sort({name: 1})
{ "_id" : ObjectId("586b98980cec8d86881cffac"), "name" : "张七" }
{ "_id" : ObjectId("586b98980cec8d86881cffa8"), "name" : "张三" }
{ "_id" : ObjectId("586b98980cec8d86881cffa9"), "name" : "李四" }
{ "_id" : ObjectId("586b98980cec8d86881cffaa"), "name" : "王五" }
{ "_id" : ObjectId("586b98980cec8d86881cffab"), "name" : "马六" }

而对于中文名字,通常有按拼音顺序排序的需求,这时就可以通过collation来搞定

db.createCollection("person", {collation: {locale: "zh"}})
db.person.insert({name: "张三"})
db.person.insert({name: "李四"})
db.person.insert({name: "王五"})
db.person.insert({name: "马六"})
db.person.insert({name: "张七"})

此时再按name字段排序,则会按照locale指定的中文规则来排序

mongo-9554:PRIMARY&gt; db.person.find().sort({name: 1})
{ "_id" : ObjectId("586b995d0cec8d86881cffae"), "name" : "李四" }
{ "_id" : ObjectId("586b995d0cec8d86881cffb0"), "name" : "马六" }
{ "_id" : ObjectId("586b995d0cec8d86881cffaf"), "name" : "王五" }
{ "_id" : ObjectId("586b995d0cec8d86881cffb1"), "name" : "张七" }
{ "_id" : ObjectId("586b995d0cec8d86881cffad"), "name" : "张三" }

MongoDB 3.4里,基本所有设计字符串字段排序的命令,都支持指定collation,比如「创建集合、创建索引、find」等;上述例子里在createCollection的时候指定了collation,则该集合里所有字符串默认都会按指定的collation来排序,如果只想针对某一个字段来指定collation,可以该字段创建指定collation的索引,例如

db.person.createIndex({name: 1}, {collation: {locale: "zh"}})

注意:如果是从3.2版本升级到3.4的,需要先执行如下命令才能使用collation特性

db.adminCommand( { setFeatureCompatibilityVersion: "3.4" } )

 

转载博客出处:

SpringBoot中MongoDB注解概念及使用

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/481933.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

清华大学药学院丁胜团队在《自然》发表突破性全能干细胞创新研究

来源&#xff1a;清华大学药学院最新科研速递 清华大学药学院丁胜教授及其团队首次发现全能干细胞的体外定向诱导及其稳定培养的药物组合&#xff0c;该突破性研究被国际顶级学术期刊《自然》&#xff08;Nature&#xff09;于北京时间2022年6月21日在线发表。该研究标…

RocketMQ:Linux下启动server和broker的命令

目录 QUESTION:RocketMQ&#xff1a;Linux下启动server和broker的命令? ANSWER: 一、启动mqnamesrv 1.1当前执行 1.2后台运行 二、启动mqbroker 2.1当前执行 2.2后台运行 QUESTION:RocketMQ&#xff1a;Linux下启动server和broker的命令? ANSWER: 一、启动mqnamesrv …

美国人如何看待超自然?

来源&#xff1a;返朴撰文&#xff1a;李品保原文刊载于《中华读书报》2022年6月22日期&#xff0c;《返朴》经授权发表。寻求超自然现象不是一种对理性的非理性反应&#xff0c;而是一种他择性合理性&#xff0c;也可将其视为美国人特定不安分的额外调解&#xff0c;这种不安分…

114名科学家Science发布关于长寿的最大规模动物研究:揭示了衰老的秘密

来源&#xff1a;生物通一个114名科学家组成的国际研究小组报告了迄今为止世界范围内最全面的关于爬行动物和两栖动物衰老和寿命的研究。在他们的许多发现中&#xff0c;他们首次记录了海龟、鳄鱼和蝾螈的衰老率特别低&#xff0c;并根据其体型延长了寿命。研究小组还发现&…

服务器上的Linux中Tomcat有时会挂掉的问题及方法

QUESTION&#xff1a;服务器上的Linux中Tomcat有时会挂掉的问题及方法? 目录 QUESTION&#xff1a;服务器上的Linux中Tomcat有时会挂掉的问题及方法? ANSWER: 一、内存不足 二、服务器内存不足 三、解决方法 3.1Tomcat内存优化 3.2代码优化内存泄漏 ANSWER: 正在启动的…

《关于加强数字政府建设的指导意见》最重要内容是这条。

来源&#xff1a;中国智慧城市论坛日前&#xff0c;国务院发布《国务院关于加强数字政府建设的指导意见》&#xff0c;我们在其中找到了让我们千呼万唤、翘首以盼、望眼欲穿的这段文字&#xff1a;强化考核评估。在各级党委领导下&#xff0c;建立常态化考核机制&#xff0c;将…

毕业设计-人脸表情识别系统、人工智能

人脸表情识别系统 1. 前言 在这个人工智能成为超级大热门的时代&#xff0c;人脸表情识别已成为其中的一项研究热点&#xff0c;而卷积神经网络、深度信念网络和多层感知器等相关算法在人脸面部表情识别领域的运用最为广泛。面部的表情中包含了太多的信息&#xff0c;轻微的表…

谷歌布莱克·勒莫因:为什么我觉得AI已觉醒了?

来源&#xff1a;科技智谷编辑&#xff1a;Light人们在 AI 身上寄托了感情&#xff0c;被一系列拟人化的 AI 术语误导&#xff0c;LaMDA 本质就是个聊天机器人。谷歌工程师布莱克勒莫因&#xff08;Blake Lemoine&#xff09;上周发布了一份他分发给同事的文件&#xff0c;引起…

阿里云数据库Mysql被黑

阿里云数据库Mysql被黑 打开Mysql查看数据库时&#xff0c;发现所有的服务器上的数据库被黑 百度翻译了一下&#xff1a; 总结一下&#xff1a; 以下是常用的可以保护数据库的方式&#xff0c;供参考。可以有效防止被攻击。 1.密码强化&#xff0c;使用复杂密码设置&#xff0…

集体心智:社会网络拓扑塑造集体认知

来源&#xff1a;集智俱乐部作者&#xff1a;Ida Momenneja译者&#xff1a;许逸聪审校&#xff1a;陈斯信编辑&#xff1a;邓一雪导语人类是社会动物&#xff0c;人类的认知也是通过在社会网络中学习和记忆而形成。人类的社会网络与其他物种不同&#xff0c;有着复杂多样的成分…

OpenAI最新研究:AI模型看看视频,就学会了玩《我的世界》

《我的世界》里&#xff0c;玩家不一定都是人类&#xff0c;现在 AI 也会玩了。来源&#xff1a;机器之心《我的世界》是全球知名度最高的开放世界游戏。小朋友只需观看十分钟的教学视频&#xff0c;就能学会在游戏中寻找稀有的钻石&#xff0c;但这却是 AI 此前无法企及的高度…

机器的崛起:隐藏的控制论历史

来源&#xff1a;sayonly在二战后的几年里&#xff0c;计算机作为一种“思维机器”是如此的新奇和未知&#xff0c;而且&#xff0c;进步似乎是无限的。新的思维机器可以计算得出如何建造摩天大楼、如何经营证券交易所以及如何飞向月球。唯一的极限是想象力。“超级大脑”是等待…

Richard Sutton:经验是AI的终极数据,四个阶段通向真正AI的发展之路

来源&#xff1a;智源社区导读&#xff1a;强人工智能的发展是近年来关注的话题。让AI从人类的感知和行为&#xff0c;而非单纯的标注数据中学习&#xff0c;成为许多研究者关注的重点。其中&#xff0c;如何利用人类习得的日常生活经验&#xff0c;启发构建能够适应不同环境&a…

一张图带你了解JRE、JDK、JVM

目录 1.JRE 2.JDK 3.JVM 三者关系&#xff1a; 1.JRE JRE是Java Runtime Environment&#xff0c;Java 运行环境&#xff0c;包含Java运行的环境和核心类库。 2.JDK JDK是 Java Development Kit&#xff0c;Java 开发工具包&#xff0c;包含Java编译工具和运行工具。 3.JV…

机器的崛起:隐藏的控制论历史(二)

来源&#xff1a;sayonly大家好&#xff0c;我是只说&#xff0c;我在《图说元宇宙》之外开了一个新的番外&#xff0c;叫《元宇宙新使命》&#xff0c;本文是第34篇&#xff0c;“机器的崛起&#xff1a;隐藏的控制论历史&#xff08;二&#xff09;”。在上一篇文章中&#x…

毕业设计-基于Python爬虫的疫情数据可视化系统

基于Python爬虫的疫情数据可视化系统 采用EChartsFlaskRequests架构&#xff1a; 源码加3105088663

不要再「外包」AI 模型了!最新研究发现:有些破坏机器学习模型安全的「后门」无法被检测到...

来源&#xff1a;AI科技评论作者&#xff1a;王玥、刘冰一、黄楠编辑&#xff1a;陈彩娴一个不可检测的「后门」&#xff0c;随之涌现诸多潜伏问题&#xff0c;我们距离「真正的」机器安全还有多远&#xff1f;试想一下&#xff0c;一个植入恶意「后门」的模型&#xff0c;别有…

Git命令:常用Git命令集合

1.Git基本工作流程 2.命令 命令作用git init初始化&#xff0c;创建 git 仓库git status查看 git 状态 &#xff08;文件是否进行了添加、提交操作&#xff09;git add 文件名添加&#xff0c;将指定文件添加到暂存区git commit -m 提交信息提交&#xff0c;将暂存区文件提交到…

从微观到宏观:涌现的实质是信息转换?

来源&#xff1a; 集智俱乐部作者&#xff1a;梁金编辑&#xff1a;邓一雪导语之前的研究表明&#xff0c;还原并非总是好的科学策略&#xff0c;一些情况下&#xff0c;降维可以增加系统元素之间的依赖性&#xff0c;使得粗粒化的宏观尺度比底层微观尺度携带更多有效信息&…

Java栈内存、堆内存、方法区对对象和引用的关系

问题&#xff1a;Java栈内存、堆内存、方法区对对象和引用的关系 答案&#xff1a; 1.单个对象 如图所示&#xff1a; &#xff08;1&#xff09;首先类加载器加载要运行的类&#xff0c;首先将main方法加载进方法区&#xff0c;并进栈内存&#xff0c;顺序执行代码&#xff…