Does Room support entity inheritance?

Danail Alexiev picture Danail Alexiev · Sep 20, 2017 · Viewed 8.8k times · Source

I am trying to migrate our project to use Room, which, by the way, I think is an awesome step forward.

I have the following structure:

public class Entity extends BaseObservable {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "_id", typeAffinity = ColumnInfo.INTEGER) 
    private long mId;

    @ColumnInfo(name = "is_dirty")
    @TypeConverters(BooleanTypeConverter.class)
    private boolean mIsDirty;

    // default constructor and accessors omitted for brevity
}

@Entity(tableName = "some_entities")
public class SomeEntity extends Entity {

    @ColumnInfo(name = "type", typeAffinity = ColumnInfo.TEXT)        
    private String mType;

    @ColumnInfo(name = "timestamp", typeAffinity = ColumnInfo.INTEGER)
    private long mTimestamp;

    // constructor, accessors
}

When I try to compile my project, it fails with no specific error.

If I try to compile it with a flat entity hierarchy, all is well.

So, my main question is: Does Room support entity inheritance? Will it be able to get the column definitions from the parent Entity class?

I would also like to know if extending BaseObservable (which I need to get the Data Binding working) can cause problems with Room? BaseObservable has one private transient field, so maybe this is causing some issues with the code generation.

Are there any recommended patterns to deal with this, or will I just have to flatten my entity hierarchy?

Answer

Danail Alexiev picture Danail Alexiev · Oct 6, 2017

After further investigation it turns out that Room Entities should not extend the BaseObservable class. It contains fields that can't be marked with @Ignore and break the code generation.

Room works well with inheritance. The annotations are processed as expected and the DB operations behave normally. You can extend from both an Entity and a POJO.