ClassCastException с использованием Morphia

Я пытаюсь получить коллекцию MongoDB и преобразовать записи в javabeans, используя Morphia, но когда я пытаюсь получить коллекцию объектов (см. Ниже в коде приложения), появляется ошибка приведения:

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

Документ

{
    "_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
    }
    ]
}

Ученик

@Entity("students")
public class Student {

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

    gets and sets

}

Гол

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

    gets and sets

}

Приложение

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 ответ

Решение

Такое же поведение испытывают и другие люди.

Не могу найти кодек для класса, Морфия, Весна.

Вы можете отправить сообщение об ошибке здесь, если считаете, что это неправильное поведение.

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

Хорошо, теперь подходит к решению. Вы можете исправить это двумя способами.

Решение 1

Вы можете удалить @Embedded аннотация от score Пойо и

замещать

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

с

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

Решение 2

Удалить @property аннотация для scores поле в Student POJO.

Другие вопросы по тегам