How to handle inheritance?

115 Views Asked by At

I'm using the Ektorp framework as Java "ORM" for CouchDB. It's using Jackson for (de)serialization of the JSON documents.

I have the following hierarchy:

public class Animal extends CouchDbDocument {
    private int numberOfLegs;
    // Getters and setters ...
}

public class Dog extends Animal {
    private String name;
    // Getters and setters
}

I have saved 3 Animals and 1 Dog to my CouchDB.

When executing List<Dog> dogs = dogRepository.getAll(), I get a collection with 4 objects (at 3 of them name is NULL). This is because Jackson/Ektorp seems to not handle inheritance by default.

So how can I handle inheritance? I would expect not getting 4 objects but only the 1 (Dog).

Update I just tried to remove the inheritance. The problem persists. So it seems Ektorp/Jackson aren't able to detect the class type.

2

There are 2 best solutions below

1
James Cootware On

Have you tried casting the value returned by getAll()?

List<Dog> dogs = (List<Dog>)dogRepository.getAll();
0
Henrik Barratt Due On

You need to instruct jackson how to handle the polymorphic type. Have a look at the jackson annotation @JsonTypeInfo