Moneta Spring Data Mongo and Jackson

Learn how to seamlessly integrate JSR354 (Java Money API) with Spring Boot and Spring Data MongoDB.

Moneta Spring Data Mongo and Jackson

Making all the things work together sometimes seems like more effort than its worth. This won’t help you with that, but if you need to get JSR354 working with Spring Boot and Spring Data MongoDB this may help you some.

The following steps assume you already have a Spring Boot app configured with Spring Data MongoDB and understand the basics of these technologies. These steps work for me with these already on classpath to start:

Jackson Money Support

To make Jackson aware of how to deal with Money add the jackson-datatype-money library to your classpath:

<dependency>  
 <groupId>org.zalando</groupId>  
 <artifactId>jackson-datatype-money</artifactId>  
 <version>1.1.1</version>  
 </dependency>

Then create a new configuration class to enable the module:

import com.fasterxml.jackson.databind.Module;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.zalando.jackson.datatype.money.MoneyModule;@Configuration  
public class JacksonConfiguration { @Bean  
  public Module moneyModule() {  
    return new MoneyModule().withMoney();  
  }  
}

Boom you are now a Money serializing fool.

Spring Data Mongo Money Support

Now to make Spring Data MongoDB understand how to convert a Money into a simple string to be stored in the database.

First create a read and write Converter. In this case to and from a string.

Read Converter

import org.javamoney.moneta.Money;  
import org.springframework.core.convert.converter.Converter;  
import org.springframework.data.convert.ReadingConverter;@ReadingConverter  
public class MoneyReadConverter implements Converter<String, Money> {  
   @Override  
   public Money convert(String moneyString) {  
     return Money.parse(moneyString);  
   }  
}

Write Converter

import org.javamoney.moneta.Money;  
import org.springframework.core.convert.converter.Converter;  
import org.springframework.data.convert.WritingConverter;@WritingConverter  
public class MoneyWriteConverter implements Converter<Money, String> { @Override  
  public String convert(Money money) {  
    return money.toString();  
  }  
}

Next override the Spring Data Mongo MongoCustomConversions in a configuration which includes your shiny new converters.

@Configuration  
public class MongoConfiguration {@Bean  
 public MongoCustomConversions mongoCustomConversions() {  
 List<Converter> converters = new ArrayList<>();  
 converters.add(new MoneyReadConverter());  
 converters.add(new MoneyWriteConverter());  
 return new MongoCustomConversions(converters);  
 }  
}

Now simply build, run and revel in your greatness.