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,並工作。謝謝! –