Reading BigDecimal with Morphia

I have a POJO that uses BigDecimal. When I save the object to morphine, it is clear that the value is saved as a string. But if I modify the database from the javascript shell to have some decimal value, try to read the object using the morphia class, it will not execute the following error:

For instance:

@Entity(value = "table_name", noClassnameStored = true) public class Advertisement implements Table { BigDecimal value; } 

 java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.ArrayList.toArray(ArrayList.java:361) at org.mongodb.morphia.utils.ReflectionUtils.convertToArray(ReflectionUtils.java:537) at org.mongodb.morphia.converters.IntegerConverter.decode(IntegerConverter.java:35) at org.mongodb.morphia.converters.DefaultConverters.fromDBObject(DefaultConverters.java:134) at org.mongodb.morphia.mapping.ValueMapper.fromDBObject(ValueMapper.java:27) at org.mongodb.morphia.mapping.Mapper.readMappedField(Mapper.java:604) at org.mongodb.morphia.mapping.Mapper.fromDb(Mapper.java:585) at org.mongodb.morphia.mapping.Mapper.fromDBObject(Mapper.java:296) at org.mongodb.morphia.query.MorphiaIterator.convertItem(MorphiaIterator.java:78) at org.mongodb.morphia.query.MorphiaIterator.processItem(MorphiaIterator.java:65) at org.mongodb.morphia.query.MorphiaIterator.next(MorphiaIterator.java:60) at org.mongodb.morphia.query.QueryImpl.asList(QueryImpl.java:294) at ... 

What is the correct form for adding a decimal value to a string form in mongodb so that morphine can read that value in Java BigDecimal?

0
source share
2 answers

Like @evanchooly links, I already had BigDecimal code that could use that object in Morphia. This is the code:

 public class BigDecimalConverter extends TypeConverter { public BigDecimalConverter() { super(BigDecimal.class); } @Override public Object encode(Object value, MappedField optionalExtraInfo) { BigDecimal val = (BigDecimal) value; if (val == null) return null; return val.toPlainString(); } @Override public Object decode(Class targetClass, Object fromDBObject, MappedField optionalExtraInfo) { if (fromDBObject == null) return null; BigDecimal dec = new BigDecimal(fromDBObject.toString()); return dec; } } 

This worked until recently when I created the new POJO collection.

Oddly enough, the workaround was to use the @Property () annotation for the variable. Instead of allowing morphine to call a key.

+2
source

You can see a discussion of this very problem on the mailing list with a few suggested solutions.

0
source

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


All Articles