2017-04-08 4 views
0

私はMongoDBのコレクションを取得し、Morphiaを使用してレコードをjavabeansに変換しようとしていますが、オブジェクトのコレクションを取得しようとすると(キャストエラーが表示されます)Morfiaを使用したClassCastException

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 

} 

の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

スコア。

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

これが正しい動作ではないと思われる場合は、ここにバグレポートを提出できます。今の溶液に来

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

わかりました。あなたは2つの方法でそれを修正することができます。

ソリューションは、1

あなたが交換してくださいscore POJOと

から@Embedded注釈を削除することができます

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

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

ソリューション2

Student POJOでscoresフィールドの@property注釈を削除します。

+0

解決策1を使用して作業しました。ありがとうございました! –

関連する問題