Mongo spring-data issue with java.util.Currency

亡梦爱人 提交于 2019-12-05 18:27:13

The Currency type is currently not supported out of the box by the Spring Data MongoDB object mapping system. You can teach Spring Data MongoDB how to convert instances of that type by providing a custom implementation of a core Spring Converter as described in the reference documentation.

public class CustomMongoConfiguration extends AbstractMongoConfiguration {

  @Bean
  @Override
  public CustomConversions customConversions() {

    Converter<Currency, String> currencyToString = source -> source.toString();
    Converter<String, Currency> stringToCurrency = source -> Currency.getInstance(source);

    return new CustomConversions(Arrays.asList(currencyToString, stringToCurrency));
  }
}

As the conversion to a String seems to be straight-forward, I create a ticket to be resolved in the upcoming version of Spring Data MongoDB.

Just in case someone else runs into @oliver-gierke's answer and get the NullPointerException like @kaluva

Spring's type resolver seems to have problems with the Lambda expression. Just change the bean definition to:

@Bean
public CustomConversions customConversions() {
    Converter<Currency, String> currencyToString = new Converter<Currency, String>() {
        @Override
        public String convert(Currency currency) {
            return currency.toString();
        }
    };

    Converter<String, Currency> stringToCurrency = new Converter<String, Currency>() {
        @Override
        public Currency convert(String s) {
            return Currency.getInstance(s);
        }
    };

    return new CustomConversions(Arrays.asList(currencyToString, stringToCurrency));
}

(I'm sorry I could not add this answer as comment to Oliver's answer. Stackoverflow won't let me.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!