I have an abstract POJO class which is named Person and two entities which are named Developer and Manager. These entities inherits Person abstract class. There is no problem to save them to the same collection but when I try to find, for instance, only developers in the collection, Morphia's find method gets me all records in the collection and I get java.lang.ClassCastException.
Morphia morphia = new Morphia();
Datastore ds = morphia.createDatastore("test");
for (Developer savedDeveloper : ds.find(Developer.class).asList()) {
System.out.println(savedDeveloper.getFoo());
}
Exception
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
So my questions is that how can I get only one specific entity list in a collection which has more than one entities?
My POJOs
Person.java
public abstract class 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;
}
}
I resolved this problem with Morphia's BasicDAO. I created a DeveloperDAO class that inherits Morphia's BasicDAO class then I used DAO methods in order to make queries and it works.
public class DeveloperDAO extends BasicDAO<Developer, String> {
public DeveloperDAO(String dbName) throws UnknownHostException {
super(MongoSingleton.getInstance(), MorphiaSingleton.getInstance(), dbName);
} }
Test
public class Test {
public static void main(String[] args) throws UnknownHostException {
DeveloperDAO developerDAO = new DeveloperDAO("test");
for(Developer developer : developerDAO.find().asList())
System.out.println(developer.getFoo());
}}