Skip to content

Room ‐ Using foreign keys

Devrath edited this page Oct 23, 2023 · 2 revisions

Why to use the foreign keys

  • With the help of foreign keys we can establish a rule-based relationship between the tables.
  • With a rule-based relationship we can ensure that operations that would cause an issue when performed can be handled in an effective way.
  • Consider a scenario below, There is a Book table and a Review table. In the table, each review given by the user is mapped to a book.
  • Now if we delete all the books without deleting the reviews associated with it. It would result in an invalid state of the tables
  • To handle the invalid states, there are certain ways we can handle like, enforcing a crash and not allowing the operation to succeed or causing an invalid operation without the crash etc...

Book.kt

@Parcelize
@Entity(
    tableName = "books",
    foreignKeys = arrayOf(
        ForeignKey(
            entity = Genre::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("bookGenreId"),
            onDelete = ForeignKey.CASCADE
        )
    )
)
class Book(
    @PrimaryKey
    @ColumnInfo(name = "id")
    val id: String = UUID.randomUUID().toString(),
    val name: String,
    val description: String,
    @ColumnInfo(name = "bookGenreId")
    val genreId: String
) : Parcelable

Review.kt

@Parcelize
@Entity(
    foreignKeys = arrayOf(
        ForeignKey(
            entity = Book::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("bookId"),
            onDelete = ForeignKey.CASCADE
        )
    )
)
data class Review(
    @PrimaryKey
    val id: String = UUID.randomUUID().toString(),
    @ColumnInfo(name = "bookId")
    val bookId: String,
    val rating: Int,
    val notes: String,
    @TypeConverters(DateConverter::class)
    val lastUpdatedDate: Date
) : Parcelable