Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascade delete based on @ForeignKey in Android Rooms ORM

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.

like image 877
Giridhar Karnik Avatar asked Sep 03 '17 08:09

Giridhar Karnik


1 Answers

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;
}
like image 154
msfreire Avatar answered Nov 06 '22 13:11

msfreire