google-code-export / morphia

Automatically exported from code.google.com/p/morphia
1 stars 0 forks source link

@Serialized doesn't work with runtime values of primitive types #377

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
morphia-0.99 / driver 2.7.2 / mongo 2.0.1

There's an issue with @Serialized when used on a field of type Object and the 
actual value is of primitive type (Integer, Long, etc).

@Entity
public class TestClass {
    @Serialized
    Object data;
}

If e.g. data = new Integer(5) it is saved as an integer property. When the 
object is read from the database, Morphia fails since it expects the property 
to be a byte[].

This problem happens because DefaultConverters.getEncoder(Object val, 
MappedField mf) looks up first in the default typed converters *before* 
searching the untyped converters where the SerializedObjectConverter resides.

Stacktrace:

Caused by: java.lang.RuntimeException: 
com.google.code.morphia.mapping.MappingException: The stored data is not a 
DBBinary or byte[] instance for TestClass.data ; it is a java.lang.Integer
    at com.google.code.morphia.mapping.ValueMapper.fromDBObject(ValueMapper.java:27)
    at com.google.code.morphia.mapping.Mapper.readMappedField(Mapper.java:497)
    at com.google.code.morphia.mapping.Mapper.fromDb(Mapper.java:480)
    ... 14 more
Caused by: com.google.code.morphia.mapping.MappingException: The stored data is 
not a DBBinary or byte[] instance for TestClass.data ; it is a java.lang.Integer
    at com.google.code.morphia.converters.SerializedObjectConverter.decode(SerializedObjectConverter.java:33)
    at com.google.code.morphia.converters.DefaultConverters.fromDBObject(DefaultConverters.java:129)
    at com.google.code.morphia.mapping.ValueMapper.fromDBObject(ValueMapper.java:25)
    ... 16 more

Original issue reported on code.google.com by sylvain.wallez on 10 Feb 2012 at 5:54

GoogleCodeExporter commented 9 years ago

Original comment by scotthernandez on 23 Feb 2012 at 6:02

GoogleCodeExporter commented 9 years ago
Following workaround seems to work:
* Wrap the @Serialized field of type Object into another class annotating with 
@Embedded. 
* Always use this class instead of the @Serialized field. This means: When you 
want to update the @Serialized field you have to update (replace) the whole 
embedded object!

Original comment by peter.fu...@gmail.com on 10 Oct 2013 at 7:43

GoogleCodeExporter commented 9 years ago
There seems not much activity on this issue but I would really be happy if 
there would be a fix for that. 
Is there a technical / conceptual reasons why not changing this behaviour?

If it is OK I could look into that and (hopefully) solve...

Original comment by peter.fu...@gmail.com on 22 Nov 2013 at 9:45