how to use foreign key in Room persistence library

Just to summarize the above posts for future readers:

The foreign key syntax in Kotlin is

@Entity(foreignKeys = arrayOf(ForeignKey(entity = ParentClass::class,
                    parentColumns = arrayOf("parentClassColumn"),
                    childColumns = arrayOf("childClassColumn"),
                    onDelete = ForeignKey.CASCADE)))

The foreign key syntax in Java is:

@Entity(foreignKeys = {@ForeignKey(entity = ParentClass.class,
    parentColumns = "parentClassColumn",
    childColumns = "childClassColumn",
    onDelete = ForeignKey.CASCADE)

Note: foreignKeys is an array, so in Java enclose @ForeignKey elements in { and }

You can refer to the official documentation for more information.

Leave a Comment