Search code examples
androidandroid-room

how to use foreign key in Room persistence library


I am working with room persistence library in android, i would appreciate if someone can help me in using foreign key, how to get data by using foreign key.


Solution

  • 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. https://developer.android.com/reference/androidx/room/ForeignKey