Cascade delete based on @ForeignKey in Android Rooms ORM
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
.
DBList
DBListContent
DBList
DBListContent
Here is the DBList
class
DBList
@Entity(tableName = "lists")
public class DBList {
@PrimaryKey
private String listId;
private String title;
private String createdDateTime;
}
Here is the DBListContent
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.
lists
listContents
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 Answer
1
I don't know it's too late to answer your question, but the mistake you have is to put @ForeignKey
in a field.
@ForeignKey
The @ForeignKeys
MUST to go in table declaration.
@ForeignKeys
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;
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.