What's the correct way to create a Room Entity with two possible Parents?

953 views Asked by At

I am using Room in Android for the first time. I have one Entity Comment which is part of a tree structure. Some comments will be the child of a Post while others will be the children of another Comment.

The following is my entity declaration

@Entity(tableName = "comments,
    foreignKeys = {
        @ForeignKey(entity = Post.class, parentColumns = "uid",
                childColumns = "post_uid", onDelete = CASCADE),
        @ForeignKey(entity = Comment.class, parentColumns = "uid",
                childColumns = "comment_uid", onDelete = CASCADE)
    }
)
public class Comment {
   ...
}

I cant see an option like nullable or required for the Foreign Key, so what is the correct way to declare that the keys can be missing?

1

There are 1 answers

5
CommonsWare On BEST ANSWER

So long as the underlying column allows NULL, you should be fine. This sample app demonstrates a tree structure, albeit one with only one possible parent. Still, the root of the tree has a null parent ID, and if that works, so should null for other foreign keys.