设置MongoDB的转换器编程(Set MongoDb converter programmatic

2019-07-04 19:11发布

我试图用一个自定义转换器与弹簧数据的MongoDB。 我想以编程方式创建它,但我得到了以下错误:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of     converting from type org.joda.time.LocalDate to type java.lang.String
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:475)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:175)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:154)
....
....

以下是失败的代码片段:

    Mongo mongo = new Mongo();
    MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, "database");

    List<Converter> converters = new ArrayList<>();
    converters.add(new LocalDateWriteConverter());
    converters.add(new LocalDateReadConverter());
    CustomConversions customConversions = new CustomConversions(converters);

    MappingContext mappingContext = new SimpleMongoMappingContext();
    MappingMongoConverter mappingMongoConverter = new MappingMongoConverter(mongoDbFactory, mappingContext);
    mappingMongoConverter.setCustomConversions(customConversions);

    MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, mappingMongoConverter);

    MongoDbEvent mongoEvent = new MongoDbEvent(new LocalDate(2012, 12, 8));
    mongoTemplate.insert(mongoEvent);

这里是我的转换器类:

class LocalDateReadConverter implements Converter<String, LocalDate> {
    @Override
    public LocalDate convert(String s) {
        // Conversion code omitted.
    }
}

class LocalDateWriteConverter implements Converter<LocalDate, String> {

    @Override
    public String convert(LocalDate localDate) {
        // Conversion code omitted.
    }
}

我想坚持的类看起来是这样的:

import org.joda.time.LocalDate;

public class MongoDbEvent {

    private String id;
    private LocalDate date;

    public MongoDbEvent(LocalDate date) {
        this.date = date;
    }

    public String getId() {
        return id;
    }

    public LocalDate getDate() {
        return date;
    }

    @Override
    public String toString() {
        return "MongoDbEvent{" +
                "id='" + id + '\'' +
                ", date=" + date +
                '}';
        }
}

Answer 1:

这个答案可能是在OP有点晚,但我只是碰到了同样的问题,今天找到了解决办法...

要以编程方式设置它,你需要调用MongoMappingConverter.afterPropertiesSet()你使用它之前。 我意识到这从阅读的代码MongoTemplate.getDefaultMongoConverter(MongoDbFactory)

下面是一个例子:

MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory, context);
converter.setTypeMapper(mapper);
converter.setCustomConversions(new CustomConversions(
        Arrays.asList(
                new TimeZoneReadConverter(),
                new TimeZoneWriteConverter()
        )
));
converter.afterPropertiesSet();
MongoTemplate template = new MongoTemplate(mongoDbFactory, converter);


Answer 2:

只是抬起头来。 我对这个问题苦苦挣扎spring-data-mongodb 1.5.1.RELEASE使用Java配置。 由于一些类已经改变了,我张贴我的解决方案。

加上以下定义与注释您的配置类@Configuration

@Bean
public Mongo mongo() throws Exception {
    MongoPropertiesResolver resolver = mongoResolver();
    return new MongoClient(resolver.getUrl());
}

@Bean
public MongoDbFactory mongoDbFactory() throws Exception {
    return new SimpleMongoDbFactory(mongo(), "database");
}

@Bean
public MongoTemplate mongoTemplate() throws Exception {
    return new MongoTemplate(mongoDbFactory(), mongoConverter());
}

@Bean
public CustomConversions customConversions() {
    List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
    converters.add(new TimeZoneReadConverter());
    converters.add(new TimeZoneReadConverter());
    return new CustomConversions(converters);
}

@Bean
public MappingMongoConverter mongoConverter() throws Exception {
    MongoMappingContext mappingContext = new MongoMappingContext();
    DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory());
    MappingMongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver, mappingContext);
    mongoConverter.setCustomConversions(customConversions());
    return mongoConverter;
}


Answer 3:

如何自定义蒙戈自定义转换器在这里描述下详细:

http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping-configuration

我注入的缺省配置值,所以我可以从application.properties配置设置中受益。

  @Configuration
  public class MongoConfiguration extends AbstractMongoConfiguration {
    @Value("${spring.data.mongodb.database:test}")
    String database;

    @Value("${spring.data.mongodb.host:localhost}:${spring.data.mongodb.port:27017}")
    String host;

    @Override
    protected String getDatabaseName() {
      return database;
    }

    @Override
    public Mongo mongo() throws Exception {
      return new MongoClient(host);
    }

    @Bean
    @Override
    public CustomConversions customConversions() {
      List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
      converterList.add(new MongoColorWriter());
      converterList.add(new MongoColorReader());
      return new CustomConversions(converterList);
    }
  }


Answer 4:

在Java 8推出java.time包的我遇到了类似的问题,在新包装使用新的和LOCALDATE类LocalDateTime。 这是我如何解决它:

我写了一个转换器,这些转换选项所有4:

  • datetolocaldatetimeconvert是
  • datetolocaldateconvert是
  • localdatetimetodateconvert是
  • localdatetodateconvert是

下面是一个例子

public class DateToLocalDateTimeConverter implements Converter<Date, LocalDateTime> {

    @Override 
    public LocalDateTime convert(Date source) { 
        return source == null ? null : LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()); 
    }
}

然后,通过包括本在MongoDB的连接,我能够在Java中与MongoDB的工作8日的xml配置(记得要添加的所有转换器):

<mongo:mapping-converter>
    <mongo:custom-converters>
        <mongo:converter>
            <bean class="package.DateToLocalDateTimeConverter" />
        </mongo:converter>
    </mongo:custom-converters>
</mongo:mapping-converter>


Answer 5:

由于org.springframework.data:spring-data-commons:1.13.3.RELEASE ,这里是如何以编程方式创建MongoTemplate自定义转换器

public MongoTemplate mongoTemplate(String mongoUri) throws Exception {
    MongoDbFactory factory = new SimpleMongoDbFactory(new MongoClientURI(mongoUri));
    CustomConversions conversions = new CustomConversions(
            Arrays.asList(new FooWriteConverter(), new FooReadConverter()));
    MongoMappingContext mappingContext = new MongoMappingContext();
    DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
    MappingMongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver, mappingContext);
    mongoConverter.setCustomConversions(conversions);
    mongoConverter.afterPropertiesSet();
    return new MongoTemplate(factory, mongoConverter);
}

(实施略)转换器

class FooWriteConverter implements Converter<Foo, DBObject> { ... }
class FooReadConverter implements Converter<DBObject, Foo> { ... }


Answer 6:

对我来说,这是我的注册转换器作为阅读器,而不是一个作家。 为了解决这个问题,你需要将@WritingConverter注释添加到您的转换器类

@Component
@WritingConverter
public class NoteWriterConverter implements Converter<Note, DBObject> {

@Override
public DBObject convert(Note source) {
    DBObject obj = new BasicDBObject();

    obj.put("title", source.getTitle());
    obj.put("reviewDate", source.getReviewDate());

    obj.removeField("_class");
    return obj;
    }
}


文章来源: Set MongoDb converter programmatically