java.lang.ClassCastException:org.bson.types.ObjectId无法强制转换为com.mongodb.DBObject

时间:2012-05-26 19:25:39

标签: java classcastexception morphia

我正在尝试使用Morphia进行项目,但是我在实体保存方面遇到了一些麻烦。我认为我的实体定义有问题,所以我尝试了他们网站上提供的那个,它抛出了这个异常。我检查了mongo,一切似乎都很好;正在创建集合,似乎有记录。

我开始组织一个简单的JUnit测试,但它不会超越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无法强制转换为com.mongodb.DBObject     在com.google.code.morphia.mapping.EmbeddedMapper.fromDBObject(EmbeddedMapper.java:149)     在com.google.code.morphia.mapping.Mapper.readMappedField(Mapper.java:433)     在com.google.code.morphia.mapping.Mapper.updateKeyInfo(Mapper.java:228)     在com.google.code.morphia.DatastoreImpl.postSaveOperations(DatastoreImpl.java:886)     在com.google.code.morphia.DatastoreImpl.postSaveGetKey(DatastoreImpl.java:683)     在com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:734)     在com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:802)     在com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:796)     在com.wtf.data.MorphiaTest.save(MorphiaTest.java:41)

我做错了什么?

1 个答案:

答案 0 :(得分:4)

尝试替换

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

import org.bson.types.ObjectId;