javamongodbmorphia

Unable to read polymorphic types with Morphia with or without the default discriminator


So I have a simple structure:

Interceptor.java

@Entity(discriminatorKey = "type")
public abstract class Interceptor {

    @Id
    protected String id;
    protected String type;

    public Interceptor(String type) {
        this.type = type;
    }
    
    // getters and setters omitted..
}

It's subclasses:

ScriptInterceptor.java

@Entity(discriminator = "script", discriminatorKey = "type")
public class ScriptInterceptor extends Interceptor {

    private String language;
    private String source;

    public ScriptInterceptor() {
        super("script");
    }
    
    // getters and setters omitted...
}

XsltInterceptor.java

@Entity(discriminator = "xslt", discriminatorKey = "type")
public class XsltInterceptor extends Interceptor {

    private String source;

    public XsltInterceptor() {
        super("xslt");
    }
    
    // getters and setters omitted...
}

The document is successfully inserted, but when reading it seems that Morphia is unable to deserialize it. The document looks like this:

The error I'm getting is:

Caused by: org.bson.codecs.configuration.CodecConfigurationException: Failed to decode 'Interceptor'. Decoding errored with: my.package.ScriptInterceptor
............
Caused by: dev.morphia.mapping.MappingException: my.package.ScriptInterceptor
    at dev.morphia.mapping.DiscriminatorLookup.lookup(DiscriminatorLookup.java:69)
    at dev.morphia.mapping.codec.pojo.EntityDecoder.getCodecFromDocument(EntityDecoder.java:105)
    ... 84 more
Caused by: java.lang.ClassNotFoundException: my.package.ScriptInterceptor
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526)

I already tried to use the default discriminator (_t) but I got the very same error.

I'm really confused right now. Why is this happening?

Server Version: 8.0.4 Driver Version: 4.11.5 Morphia Version: 2.4.15


EDIT

Looks like an issue with the MongoDB driver. Since current Morphia stable release (2.4.15) does not support the most recent versions of the driver (5.X), the problem most likely resides here.

The very same code worked flawlessly with Morphia 3.0.0 (which brings the 5.X driver), but currently it is a SNAPSHOT version. Anyways, I might stick with that.

If anyone has a fix for the 2.4.15, please, leave an answer and share with us.


Solution

  • There's a Morphia 2.5 now that brings driver 5.0+ support, fwiw. 2.4.x and 2.5.x only differ in what drivers they support so the transition should be seamless for you.