Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Room support entity inheritance?

Tags:

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?

like image 685
Danail Alexiev Avatar asked Sep 20 '17 08:09

Danail Alexiev


People also ask

What is entity in room database?

A Room entity includes fields for each column in the corresponding table in the database, including one or more columns that comprise the primary key.

Can the entity class inherit from non entity classes?

Entities may have non-entity superclasses, and these superclasses can be either abstract or concrete. The state of non-entity superclasses is nonpersistent, and any state inherited from the non-entity superclass by an entity class is nonpersistent.

What is abstract entity in java?

An abstract class may be declared an entity by decorating the class with @Entity. Abstract entities are like concrete entities but cannot be instantiated.


1 Answers

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.

like image 151
Danail Alexiev Avatar answered Oct 11 '22 18:10

Danail Alexiev