javascript
MongoDB:SpringBoot有关@Document(collection = )与@Document(collation= )注解的区别
?
目錄
?
QUESTION:SpringBoot有關(guān)@Document(collection = "")與@Document(collation= "")注解的區(qū)別?
ANSWER:
一、問題原因
二、分析
2.1 Collection
@Id
@Document
@Indexed
@CompoundIndex
@Field
@Transient
@DBRef
2.2 Collation
2.2.1特性
2.2.2示例
轉(zhuǎn)載博客出處:
?
?
?
QUESTION:SpringBoot有關(guān)@Document(collection = "")與@Document(collation= "")注解的區(qū)別?
?
ANSWER:
在啟動(dòng)項(xiàng)目時(shí),報(bào)出如下異常:
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"}一、問題原因
經(jīng)查找,'failed to add collation information to index spec for index creation:是指出了異常的問題。
在一個(gè)實(shí)體類中使用了:
@Document(collation = "message")這里應(yīng)該變?yōu)?
@Document(collection = "message")二、分析
這里區(qū)分一下兩者的區(qū)別:
2.1 Collection
?
@Id
主鍵,不可重復(fù),自帶索引,可以在定義的列名上標(biāo)注,需要自己生成并維護(hù)不重復(fù)的約束。如果自己不設(shè)置@Id主鍵,mongo會(huì)自動(dòng)生成一個(gè)唯一主鍵,并且插入時(shí)效率遠(yuǎn)高于自己設(shè)置主鍵。原因可參考上一篇mongo和mysql的性能對(duì)比。?
在實(shí)際業(yè)務(wù)中不建議自己設(shè)置主鍵,應(yīng)交給mongo自己生成,自己可以設(shè)置一個(gè)業(yè)務(wù)id,如int型字段,用自己設(shè)置的業(yè)務(wù)id來維護(hù)相關(guān)聯(lián)的表。
@Document
標(biāo)注在實(shí)體類上,類似于hibernate的entity注解,標(biāo)明由mongo來維護(hù)該表。
org.springframework.data.mongodb.core.mapping.Document.class
把一個(gè)java類聲明為mongodb的文檔,可以通過collection參數(shù)指定這個(gè)類對(duì)應(yīng)的文檔。
@Document(collection="mongodb 對(duì)應(yīng) collection 名") ? ? ?
// 若未加 @Document ,該 bean save 到 mongo 的 user collection
// 若添加 @Document ,則 save 到 reUser collection
@Indexed
聲明該字段需要加索引,加索引后以該字段為條件檢索將大大提高速度。?
唯一索引的話是@Indexed(unique = true)。?
也可以對(duì)數(shù)組進(jìn)行索引,如果被索引的列是數(shù)組時(shí),MongoDB會(huì)索引這個(gè)數(shù)組中的每一個(gè)元素。?
也可以對(duì)整個(gè)Document進(jìn)行索引,排序是預(yù)定義的按插入BSON數(shù)據(jù)的先后升序排列。?
也可以對(duì)關(guān)聯(lián)的對(duì)象的字段進(jìn)行索引,譬如User對(duì)關(guān)聯(lián)的address.city進(jìn)行索引。(注解怎么寫還不清楚,待查)
@CompoundIndex
復(fù)合索引,加復(fù)合索引后通過復(fù)合索引字段查詢將大大提高速度。
寫法如上,lastName和age將作為復(fù)合索引,數(shù)字參數(shù)指定索引的方向,1為正序,-1為倒序。方向?qū)捂I索引和隨機(jī)存不要緊,但如果你要執(zhí)行分組和排序操作的時(shí)候,它就非常重要了。
@Field
代表一個(gè)字段,可以不加,不加的話默認(rèn)以參數(shù)名為列名。
給映射存儲(chǔ)到 mongodb 的字段取別名
在 java bean 中字段名為 firstName,存儲(chǔ)到 mongo 中 key 為 fName
? ?
@Transient
被該注解標(biāo)注的,將不會(huì)被錄入到數(shù)據(jù)庫中。只作為普通的javaBean屬性。
@DBRef
?
關(guān)聯(lián)另一個(gè)document對(duì)象。類似于mysql的表關(guān)聯(lián),但并不一樣,mongo不會(huì)做級(jí)聯(lián)的操作。?
先來看一下不加DBRef時(shí),mongo保存數(shù)據(jù)的情況:?
Article類有String title,List pictureList,兩個(gè)屬性,Picture有一個(gè)url,一個(gè)desc屬性。新建數(shù)個(gè)Picture對(duì)象,并賦值給Article的list,執(zhí)行Article的insert操作,mongo保存的結(jié)果如圖:?
?
list會(huì)作為普通的數(shù)據(jù)存到article里,并不會(huì)為Picture建表,這一點(diǎn)是區(qū)別于mysql的級(jí)聯(lián)存儲(chǔ)的。
在Article里給list加上DBRef注解后就不同了?
?
再次執(zhí)行添加Article操作后,看結(jié)果?
?
發(fā)現(xiàn)就不再是直接顯示的Picture的各個(gè)屬性了,而是只保存了Picture的id和namespace,同時(shí)仍然沒有創(chuàng)建Picture的collection(等同于mysql的表)。?
如此此時(shí)查詢該Article,會(huì)發(fā)現(xiàn)list為空,并沒有關(guān)聯(lián)上Picture的值。其實(shí)上一步已經(jīng)發(fā)現(xiàn)了,系統(tǒng)并沒有去創(chuàng)建Picture的表。那即便Article關(guān)聯(lián)了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.意思就是不會(huì)處理級(jí)聯(lián)保存,你必須單獨(dú)處理關(guān)聯(lián)的對(duì)象。?
現(xiàn)在修改一下添加Article的代碼,先做Picture的持久化操作。?
?
再看結(jié)果,發(fā)現(xiàn)Picture已經(jīng)被持久化,再次查詢該Article時(shí),相應(yīng)的Picture也全部查了出來。?
如果在Article里刪除關(guān)聯(lián)的list,set為null并保存,系統(tǒng)只會(huì)刪掉Article里關(guān)聯(lián)的list,而Picture對(duì)象本身的數(shù)據(jù)是不會(huì)被刪除的。?
從上面看來,貌似DBRef比較雞肋,而且甚至有時(shí)還會(huì)帶著誤導(dǎo)的性質(zhì),譬如Article關(guān)聯(lián)了兩個(gè)空的Picture時(shí)在Article還能看到2個(gè)對(duì)象的引用,然后2個(gè)對(duì)象并不存在,是查詢不出來的。?
那么這個(gè)標(biāo)簽存在的意義何在?
官方的說法是:?
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.?
實(shí)際使用中,感覺貌似作用是在不同的表做劃分吧,有點(diǎn)模擬mysql外鍵的意思。免得數(shù)據(jù)都落到一個(gè)大表的,不便于做關(guān)聯(lián)的表的查詢。
?
?
2.2 Collation
?
2.2.1特性
Collation的3.4版本新特性。
拼寫允許用戶在字符串比較中使用特殊語言-特殊規(guī)則,例如字母拼寫和口音標(biāo)記規(guī)則。
你可以為一個(gè)收藏或視圖、索引或支持拼寫的具體操作做特色拼寫。
一份拼寫文件有以下字段:
?
當(dāng)具體的拼寫時(shí),當(dāng)?shù)氐钠磳懯菑?qiáng)制性的;所有其他拼寫是可選的。點(diǎn)擊查看官方文檔: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: "張七"})默認(rèn)情況下,名字字段會(huì)被當(dāng)做一個(gè)普通的二機(jī)制字符串來對(duì)比,按照name字段排序的結(jié)果如下
mongo-9554:PRIMARY> 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" : "馬六" }而對(duì)于中文名字,通常有按拼音順序排序的需求,這時(shí)就可以通過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: "張七"})此時(shí)再按name字段排序,則會(huì)按照locale指定的中文規(guī)則來排序
mongo-9554:PRIMARY> 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里,基本所有設(shè)計(jì)字符串字段排序的命令,都支持指定collation,比如「創(chuàng)建集合、創(chuàng)建索引、find」等;上述例子里在createCollection的時(shí)候指定了collation,則該集合里所有字符串默認(rèn)都會(huì)按指定的collation來排序,如果只想針對(duì)某一個(gè)字段來指定collation,可以該字段創(chuàng)建指定collation的索引,例如
db.person.createIndex({name: 1}, {collation: {locale: "zh"}})注意:如果是從3.2版本升級(jí)到3.4的,需要先執(zhí)行如下命令才能使用collation特性
db.adminCommand( { setFeatureCompatibilityVersion: "3.4" } )?
轉(zhuǎn)載博客出處:
SpringBoot中MongoDB注解概念及使用
?
?
總結(jié)
以上是生活随笔為你收集整理的MongoDB:SpringBoot有关@Document(collection = )与@Document(collation= )注解的区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 国科大prml15-基于浅层模型的计算机
- 下一篇: 13 计算机组成原理第七章 输入/输出