Created
August 29, 2011 23:42
-
-
Save harlanji/1179718 to your computer and use it in GitHub Desktop.
Best way to add custom converters to spring-data-mongodb?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
@greenlaw110, good ideas, saved me a lot of debugging time
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 ;)
After much searching, I found this example to be more elegant: https://github.com/eugenp/tutorials/blob/master/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java
Since the link from @mpereira-dev isn't up-to-date anymore here are some new ones:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Issue found! Need to call
afterPropertiesSet()
. Here is the new code that works: