整合MongoDB踩坑記錄及解決方法

1、連接遠程MongoDB失敗

問題:
com.mongodb.MongoSocketOpenException: Exception opening socket

原因:
由於添加了依賴:spring-boot-starter-data-mongodb,因此,SpringBoot程序啓動時會自動配置並連接MongoDB,但自動連接的配置內容與自己定義的不同,因此會導致連接失敗,而且當然要連接自己的配置的東西

解決:
因此要在SpringBoot啓動類的@SpringBootApplication後面加上exclude = MongoAutoConfiguration.class,即:


@SpringBootApplication(exclude = MongoAutoConfiguration.class)

 



2、MongoDB依賴版本問題

問題:
An attempt was made to call a method that does not exist. The attempt was made from the following location
顯示的有關Jar包爲:mongodb-data-core-4.2.3.jar

解決:
在IDEA打開依賴的UML圖,找到各pom文件對應UML圖的mongodb-data-core,逐個雙擊,得知spring-boot-starter-data-mongodb 2.5.2最高僅支持mongodb-data-core 4.2.3,因此我將所有pom文件中的mongodb-data-sync的版本由4.3.0改爲4.2.3(mongodb-data-sync與mongodb-data-core有關聯),形成版本統一,就可找到mongodb-data-core 4.2.3來執行對應的MongoDB內容
3、MongoTemplate注入失敗

問題:
required a bean of type ‘org.springframework.data.mongodb.core.MongoTemplate’ that could not be found

原因:
SpringBoot的版本較高,不支持直接注入MongoTemplate,即僅使用下述內容會出現上述錯誤:

@Autowired
private MongoTemplate mongoTemplate;

 


解決:
截止2021.08.25,內外網都找不到最佳的解決方案,因此我翻看了SpringDataMongoDB 3.2.4的官方文檔,結合所學得到解決方案
部分官方文檔如下:
11.4. Introduction to MongoTemplate

The MongoTemplate class, located in the org.springframework.data.mongodb.core package, is the central class of Spring’s MongoDB support and provides a rich feature set for interacting with the database. The template offers convenience operations to create, update, delete, and query MongoDB documents and provides a mapping between your domain objects and MongoDB documents.

Once configured, MongoTemplate is thread-safe and can be reused across multiple instances.

The mapping between MongoDB documents and domain classes is done by delegating to an implementation of the MongoConverter interface. Spring provides MappingMongoConverter, but you can also write your own converter. See “Custom Conversions - Overriding Default Mapping” for more detailed information.

The MongoTemplate class implements the interface MongoOperations. In as much as possible, the methods on MongoOperations are named after methods available on the MongoDB driver Collection object, to make the API familiar to existing MongoDB developers who are used to the driver API. For example, you can find methods such as find, findAndModify, findAndReplace, findOne, insert, remove, save, update, and updateMulti. The design goal was to make it as easy as possible to transition between the use of the base MongoDB driver and MongoOperations. A major difference between the two APIs is that MongoOperations can be passed domain objects instead of Document. Also, MongoOperations has fluent APIs for Query, Criteria, and Update operations instead of populating a Document to specify the parameters for those operations.

The preferred way to reference the operations on MongoTemplate instance is through its interface, MongoOperations.

The default converter implementation used by MongoTemplate is MappingMongoConverter. While the MappingMongoConverter can use additional metadata to specify the mapping of objects to documents, it can also convert objects that contain no additional metadata by using some conventions for the mapping of IDs and collection names. These conventions, as well as the use of mapping annotations, are explained in the “Mapping” chapter.

Another central feature of MongoTemplate is translation of exceptions thrown by the MongoDB Java driver into Spring’s portable Data Access Exception hierarchy. See “Exception Translation” for more information.

MongoTemplate offers many convenience methods to help you easily perform common tasks. However, if you need to directly access the MongoDB driver API, you can use one of several Execute callback methods. The execute callbacks gives you a reference to either a com.mongodb.client.MongoCollection or a com.mongodb.client.MongoDatabase object. See the “Execution Callbacks” section for more information.

The next section contains an example of how to work with the MongoTemplate in the context of the Spring container.
11.4.1. Instantiating MongoTemplate

You can use Java to create and register an instance of MongoTemplate, as the following example shows:

Example 61. Registering a com.mongodb.client.MongoClient object and enabling Spring’s exception translation support


@Configuration
public class AppConfig {
    @Bean
    public MongoClient mongoClient() {
        return MongoClients.create("mongodb://localhost:27017");
    }
    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoClient(), "mydatabase");
    }
}

 



There are several overloaded constructors of MongoTemplate:

    MongoTemplate(MongoClient mongo, String databaseName): Takes the MongoClient object and the default database name to operate against.
    MongoTemplate(MongoDatabaseFactory mongoDbFactory): Takes a MongoDbFactory object that encapsulated the MongoClient object, database name, and username and password.
    MongoTemplate(MongoDatabaseFactory mongoDbFactory, MongoConverter mongoConverter): Adds a MongoConverter to use for mapping.

You can also configure a MongoTemplate by using Spring’s XML <beans/> schema, as the following example shows:


<mongo:mongo-client host="localhost" port="27017"/>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  <constructor-arg ref="mongoClient"/>
  <constructor-arg name="databaseName" value="geospatial"/>
</bean>

 



Other optional properties that you might like to set when creating a MongoTemplate are the default WriteResultCheckingPolicy, WriteConcern, and ReadPreference properties.

The preferred way to reference the operations on MongoTemplate instance is through its interface, MongoOperations.

由文檔可知,與之前大不相同,需要手動創建MongoDB配置類:
@Configuration
public class MongoDBConfig {
    @Bean
    public MongoClient mongoClient() {
        return MongoClients.create("mongodb://localhost:27017");
    }
    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoClient(), "mydatabase");
    }
}

 



其中localhost爲要連接的MongoDB所在主機的IP,mydatabase爲要連接的MongoDB數據庫
再到要使用MongoTemplate的類中添加下述內容:

@Autowired
private MongoTemplate mongoTemplate;

 



4、MongoTemplate的findById返回Null

有2種情況:
(1) MongoDB的集合中數據的主鍵_id爲ObjectId類型,傳入的id爲String類型
(2) MongoDB的集合中數據的主鍵_id爲String類型,傳入的id爲ObjectId類型
第2種情況容易被忽視,需要修改MongoDB的集合

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章