我正在尝试使用Morphia获取MongoDB的集合并将记录转换为javabeans,但是当我尝试获取对象集合时(请参阅下面的应用程序代码),会出现强制转换错误:
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();
}
答案 0 :(得分: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.