整合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的集合

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