Search code examples
javaclasscastexceptionmorphia

java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to com.mongodb.DBObject


I'm trying to use Morphia for a project but I'm having some trouble getting entities to save. I figured something was wrong with my entity definition so I tried the one provided on their site and it throws this exception. I checked mongo and everything seems to be fine; the collections are being created and there appear to be records.

I started to put together a simple JUnit test, but it won't get beyond datastore.save(e):

package com.wtf.data;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.emul.org.bson.types.ObjectId;
import com.mongodb.Mongo;
import org.junit.Test;

import java.net.UnknownHostException;

public class MorphiaTest {
    @Entity
    class MyEntity {
        @Id
        ObjectId id;
        String name;
    }

    @Test
    public void save() {
        Mongo mongo = null;
        try {
            mongo = new Mongo("127.0.0.1", 27017);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        Morphia morphia = new Morphia();
        morphia.map(MyEntity.class);
        Datastore datastore = morphia.createDatastore(mongo, "MorphiaTest");
        datastore.ensureIndexes();

        MyEntity e = new MyEntity();
        datastore.save(e);
    }
}

java.lang.RuntimeException: java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to com.mongodb.DBObject at com.google.code.morphia.mapping.EmbeddedMapper.fromDBObject(EmbeddedMapper.java:149) at com.google.code.morphia.mapping.Mapper.readMappedField(Mapper.java:433) at com.google.code.morphia.mapping.Mapper.updateKeyInfo(Mapper.java:228) at com.google.code.morphia.DatastoreImpl.postSaveOperations(DatastoreImpl.java:886) at com.google.code.morphia.DatastoreImpl.postSaveGetKey(DatastoreImpl.java:683) at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:734) at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:802) at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:796) at com.wtf.data.MorphiaTest.save(MorphiaTest.java:41)

What am I doing wrong?


Solution

  • Try to replace

    import com.google.code.morphia.emul.org.bson.types.ObjectId;
    

    with

    import org.bson.types.ObjectId;