Skip to content

Instantly share code, notes, and snippets.

@harlanji
Created August 29, 2011 23:42
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save harlanji/1179718 to your computer and use it in GitHub Desktop.
Save harlanji/1179718 to your computer and use it in GitHub Desktop.
Best way to add custom converters to spring-data-mongodb?
MongoTemplate mongo = ...;
List<Converter> converters = new ArrayList<Converter>();
converters.add(new Converter<DBObject, Participant>() {
public Participant convert(DBObject s) {
throw new UnsupportedOperationException("Not supported yet 1.");
}
});
converters.add(new Converter<Participant, DBObject>() {
public DBObject convert(Participant s) {
throw new UnsupportedOperationException("Not supported yet 2.");
}
});
CustomConversions cc = new CustomConversions(converters);
((MappingMongoConverter)mongo.getConverter()).setCustomConversions(cc);
@elidzah
Copy link

elidzah commented Dec 10, 2016

save a lot of debugging also for me. Trying to set a CustomConversions on multiple database repositories. the interesting part is:

    m_ = new MongoTemplate(client, db);
    Converter[] ca = new Converter[]{new ObCriteria.TypeWriteConverter(), new ObCriteria.TypeReadConverter()};
    CustomConversions cc = new CustomConversions(Arrays.asList(ca));
    MappingMongoConverter mmc = (MappingMongoConverter)m_.getConverter();
    mmc.setCustomConversions(cc);
    mmc.afterPropertiesSet(); 

in Mongo Template override. My Template override looks like the following:

@Override
@Bean(name = "mongoCTGTEmplate")
public MongoTemplate mongoTemplate() throws Exception {
    MongoTemplate m_ = new MongoTemplate(this.mongo(), databaseCTG);

    MappingMongoConverter mmc = (MappingMongoConverter) m_.getConverter();
    mmc.setCustomConversions(this.customConversions());
    mmc.afterPropertiesSet();
    return m_;
}

I spent a lot of time on the web looking for the solution, and find it here! thanks ;)

@mpereira-dev
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment