Morphia: inheritance not handled properly?

982 Views Asked by At

I have a class that implements an interface. Why are the arraylist contents not stored in the database? Here is some code to illustrate the problem.

The class

@Entity
public class MyClass implements MyInterface {

@Id
@Indexed
public String id;

public String someField;

public MyClass(String id, String someField){
    this.id = id;
    this.someField = someField;
}
}

The interface

public interface MyInterface {

@Embedded
public List<String> mylist = new ArrayList<String>();
}

Test code

@Test
public void test() {
    testInheritance();
}

public void testInheritance() {
    MyClass myClass = new MyClass("test", "someField");
    myClass.myList.add("wow");
    MyClassDao dao = new MyClassDao();
    dao.save(myClass);
}

public class MyClassDao extends BasicDAO<MyClass, ObjectId> {

    public MyClassDao() {
        super(MyClass.class, MorphiaManager.getMongoClient(), MorphiaManager.getMorphia(), MorphiaManager.getDB().getName());
    }
}

Result in DB

{
"_id" : "test",
"className" : "gr.iti.mklab.simmo.util.MyClass",
"someField" : "someField"
}
1

There are 1 best solutions below

0
On BEST ANSWER

Interfaces can only declare method signatures and constants (static final variables). What you want to use is an abstract base class from which you inherit.

Additional observations from your code:

  • The id should be ob the type ObjectId and is automatically indexed, you don't need the @Indexed
  • Attributes should be private or protected and you need to provide getters and setters for them
  • You need a default no-arg constructor in your entity class