我终于找到了解决方案。可能不是最好的选择,但有效。
我所做的是将转换器从使用String
中删除。这样,我创建了以下 Mongo 转换器:ObjectId
MongoTemplate
QueryMapper
public class CustomMongoConverter extends MappingMongoConverter {
public CustomMongoConverter(MongoDbFactory mongoDbFactory, MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
super(mongoDbFactory, mappingContext);
conversionService.addConverter(new Converter<String, ObjectId>() {
@Override
public ObjectId convert(String source) {
throw new RuntimeException();
}
});
}
}
然后,我将转换器的实现传递给MongoTemplate
:
<bean id="mongoConverter" class="com.abcompany.model.repositories.utils.CustomMongoConverter">
<constructor-arg ref="mongoDbFactory"/>
<constructor-arg>
<bean class="org.springframework.data.mongodb.core.mapping.MongoMappingContext"/>
</constructor-arg>
</bean>
<bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">
<constructor-arg ref="mongoDbFactory"/>
<constructor-arg ref="mongoConverter"/>
</bean>
这样,当尝试从 String 转换为 ObjectId 时,它会引发异常并且不会执行此操作。请注意,您可能只需从conversionService
.