Cascade delete based on @ForeignKey in Android Rooms ORM

14k views Asked by At

I have two entities DBList adnd DBListContent. With one to many relationship between DBList and DBListContent.

Here is the DBList class

@Entity(tableName = "lists")
public class DBList {
    @PrimaryKey
    private String listId;
    private String title;
    private String createdDateTime;
}

Here is the DBListContent

@Entity(tableName = "listContents")
public class DBListContent {
    @PrimaryKey
    public String listContentId;
    public String content;
    public String lastEditedBy;
    public String lastEditedDateTime;

    @ForeignKey(entity = DBList.class, parentColumns = "listId", childColumns = "dbListId", onDelete = CASCADE)
    public String dbListId;
}

When I delete a row in lists table, the corresponding rows in the listContents table are not deleted.

I deleted the rows using the following Dao methods

@Delete
void deleteLists(List<DBList> dbLists);

@Query("delete from lists")
void deleteLists();

I know I am missing something pretty obvious. Please guide me in this.

1

There are 1 answers

0
msfreire On

I don't know it's too late to answer your question, but the mistake you have is to put @ForeignKey in a field.

The @ForeignKeys MUST to go in table declaration.

Your code should look like that.

@Entity(tableName = "listContents",foreignKeys ={
    @ForeignKey(onDelete = CASCADE,entity = DBList.class,
    parentColumns = "listId",childColumns = "dbListId")},
    indices = {
            @Index("dbListId"),
    })
public class DBListContent {
    @PrimaryKey
    public String listContentId;
    public String content;
    public String lastEditedBy;
    public String lastEditedDateTime;
    public String dbListId;
}