android – how to use foreign key in Room persistence library-ThrowExceptions

Exception or error:

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.

How to solve:

There is a nice tutorial that i used :

https://medium.com/@tonyowen/room-entity-annotations-379150e1ca82

it alse give informations about : @embeded, @ignore,@ColumnInfo

When we use foreign key dont forget to put onDelete = ForeignKey.CASCADE this way if you delete an data it will also delete de dependency. This way you won’t have false data or data that are never use

###

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))

You can refer to the official documentation for more information.
https://developer.android.com/reference/android/arch/persistence/room/ForeignKey.html

Leave a Reply

Your email address will not be published. Required fields are marked *