2017-04-08 76 views
0

我試圖獲取MongoDB的集合並將記錄轉換爲使用Morphia的javabeans,但是當我嘗試獲取對象的集合(請參閱下面的應用程序代碼)時,會出現一個投射錯誤:使用Morphia的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 

} 

應用

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

好了,現在來解決。你可以通過兩種方式解決它。

解決方案1 ​​

您可以從score POJO和

刪除@Embedded註釋更換

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

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

溶液2

Student POJO卸下@property註解爲scores字段。

+0

我用解決方案1,並工作。謝謝! –