Morphine BigDecimal Conservation Problem

I use morphia to save an object, that one of its fields is BigDecimal.

@Entity class MyObject { BigDecimal myField; } 

And I'm trying to save it in db:

  Morphia morphia = new Morphia(); Datastore datastore = morphia.createDatastore(new MongoClient("localhost"), "myStore"); morphia.getMapper().getConverters().addConverter(new BigDecimalConverter()); MyObject foo = new MyObject (); foo.setMyField(new BigDecimal("1.1111111111111111")); datastore.save(foo); 

But I get the following exception:

  Caused by: java.lang.RuntimeException: java.lang.NumberFormatException: Conversion to Decimal128 would require inexact rounding of 1.111111111111111160454356650006957352161407470703125 at org.mongodb.morphia.mapping.ValueMapper.toDBObject(ValueMapper.java:29) at org.mongodb.morphia.mapping.Mapper.writeMappedField(Mapper.java:867) at org.mongodb.morphia.mapping.Mapper.toDBObject(Mapper.java:982) ... 7 more 
+5
source share
2 answers

As you mentioned, the Morphia package has its own BigDecimalConverter, which you can register with the object. But if you need some other behavior, you can create your own converter. For example, when I needed to change the implementation of the BigDecimalConverter encoding, I extended this class by overriding this method. Check out the following implementation.

 public class CustomBigDecimalConverter extends org.mongodb.morphia.converters.BigDecimalConverter { public CustomBigDecimalConverter() { super(); } @Override public Object encode(final Object value, final MappedField optionalExtraInfo) { if (value instanceof BigDecimal) { return ((BigDecimal) value).setScale(10, RoundingMode.CEILING); } return super.encode(value, optionalExtraInfo); } } 
+6
source

Please also note that some people have encountered problems with BigDecimal and older versions of the java driver. (See this question .) Make sure you have mongo-java version 3.5.0 or later.

0
source

Source: https://habr.com/ru/post/1273017/


All Articles