Search code examples
android-sqlitedatabase-migrationandroid-room

Room database handling inheritance in POJO and multiple tables


I have an issue while migrating from sqlite to Room. I have 1 parent and 1 child class and 2 tables corresponding to it.

I have inheritance as follows

public class Sms {
    int _id;
    String sender;
    String body;
    Date date;
} 

public class Event extends Sms {
    String eventName;
    long eventDueDate;
}

And I have tables as

SmsTable >>  
_id INTEGER NOT NULL primary key autoincrement,
sender TEXT not null,
body TEXT not null,
date INTEGER not null

EventTable >>
_id INTEGER NOT NULL primary key autoincrement,
sms_id INTEGER,
eventName TEXT not null,
eventDueDate INTEGER

Now when I define Event as @Entity(tableName = "EventTable") it gives me an error that Migration didn't properly handle Events as expected TableInfo and found TableInfo doesn't match.

Expected Table Info has columns for sender, body, date while my EventTable doesn't have them.

How do I migrate my Event class which has inherited from Sms but tables are not flattened ?

P.s. I can not flatten the EventTable as SmsTable exists even without Event and I need to convert Sms also into Entity.


Solution

  • IgnoredColumns : In cases where an entity inherits fields from a parent entity, it's usually easier to use the ignoredColumns property of the @Entity attribute.

    foreignKeys : Even though you cannot use direct relationships, Room still allows you to define Foreign Key constraints between entities.

    @Entity(tableName = "EventTable", ignoredColumns = "sender","body","date",
           foreignKeys = @ForeignKey(entity = Sms.class,
            parentColumns = "id" , childColumns = "sms_id"))
    
            public class Event extends Sms {
    
            @PrimaryKey(autoGenerate = true)
            @ColumnInfo(name = "_id")
             public int id;
    
             @ColumnInfo(name = "sms_id")
              public int smsId;
    
             public String evwntName;
             public long eventDuedate;
    
        }