我有一個名爲Person的抽象POJO類和兩個名爲Developer和Manager的實體。這些實體繼承Person抽象類。將它們保存到同一個集合中沒有問題,但是當我嘗試查找集合中的開發人員時,Morphia的find方法將所有記錄都收集到集合中,並且我得到java.lang.ClassCastException。如何在與Morphia相同的集合中找到不同的實體
Morphia morphia = new Morphia();
Datastore ds = morphia.createDatastore("test");
for (Developer savedDeveloper : ds.find(Developer.class).asList()) {
System.out.println(savedDeveloper.getFoo());
}
異常
Sep 27, 2013 11:56:18 AM com.google.code.morphia.logging.MorphiaLoggerFactory chooseLoggerFactory
INFO: LoggerImplFactory set to com.google.code.morphia.logging.jdk.JDKLoggerFactory
Developer1
Developer2
Exception in thread "main" java.lang.ClassCastException: test.model.Manager cannot be cast to test.model.Developer
at test.Test.main(Test.java:39)
Java Result: 1
所以我的問題是,我怎麼能擁有一個以上的實體集合中只得到一個特定的實體列表?
我的POJO
Person.java
公共抽象類Person {
@Id private ObjectId objectid; private String username; public Person() { } /* ......Getters and Setters*/ }
People.java
@Entity("people")
public class Developer extends Person {
private String foo;
public Developer() {
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
Manager.java
@Entity("people")
public class Manager extends Person {
private String bar;
public Developer() {
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
請嘗試: 'ds.find(Developer.class).filter( 「類名」,Developer.class.getName());' –