ClassCastException using Morphia

这一生的挚爱 提交于 2020-01-07 04:48:08

问题


I'm trying to get a collection of MongoDB and convert the records into javabeans using Morphia, but when I try to get the collection of objects (see below in App code), a cast error appears:

Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to com.homework.Score

Document

{
    "_id" : 19,
    "name" : "Student 01",
    "scores" : [
    {
        "type" : "exam",
        "score" : 44.51211101958831
    },
    {
        "type" : "quiz",
        "score" : 0.6578497966368002
    },
    {
        "type" : "homework",
        "score" : 93.36341655949683
    },
    {
        "type" : "homework",
        "score" : 49.43132782777443
    }
    ]
}

Student

@Entity("students")
public class Student {

@Id
private int id;
@Property("name")
private String name;
@Property("scores")
private List<Score> scores;

    gets and sets

}

Score

@Embedded
public class Score {
@Property("type")
private String type;
@Property("score")
private double score;

    gets and sets

}

App

private static MongoClient client = new MongoClient();
private static final Morphia morphia = new Morphia();
private static Datastore datastore;
private static Query<Student> query;

public static void main(String[] args) {

    morphia.mapPackage("com.homework");
    datastore = morphia.createDatastore(client, "school");
    datastore.ensureIndexes();
    query = datastore.createQuery(Student.class);
    List<Student> students = query.asList();

    List<Score> scoresCurr;
    Score score1;
    Score score2;
    int idx;

    for (Student s : students) {
        scoresCurr = s.getScores();

        score1 = scoresCurr.get(2);     <<<< exception occurs here

        score2 = scoresCurr.get(3);
        idx = score1.getScore() < score2.getScore() ? 2 : 3;
        scoresCurr.remove(idx);
        s.setScores(scoresCurr);
        datastore.save(s);
    }

    client.close();
}

回答1:


This is the similar behavior other people have also experienced.

Can't find a codec for class , Morphia , Spring.

You can file a bug report here if you feel this is not the right behavior.

https://github.com/mongodb/morphia/issues

Okay now coming to the solution. You can fix it two ways.

Solution 1

You can remove the @Embedded annotation from score pojo and

Replace

@Property("scores") private List<Score> scores;

with

@Embedded("scores") private List<Score> scores;

Solution 2

Remove the @property annotation for scores field in Student pojo.



来源:https://stackoverflow.com/questions/43299998/classcastexception-using-morphia

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!