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 1:

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

Solution 2:

Here how you can define and access a One-to-many (Foreign Key) relationship in Android Jetpack Room. Here the Entities are Artist and Album and the foreign key is Album.artist

@Entity
data class Artist(
    @PrimaryKey
    val id: String,
    val name: String
)

@Entity(
    foreignKeys = [ForeignKey(
        entity = Artist::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("artist"),
        onDelete = ForeignKey.CASCADE
    )]
)
data class Album(
    @PrimaryKey
    val albumId: String,
    val name: String,
    @ColumnInfo(index = true)
    val artist: String
)

then the embedded object (read official Android documentation: Define relationships between objects)

data class ArtistAndAlbums(
    @Embedded
    val artist: Artist,
    @Relation(
        parentColumn = "id",
        entityColumn = "artist"
    )
    val albums: List<Album>
)

And finally the DAO

@Dao
interface Library {
    @Insert
    suspend fun save(artist: Artist)

    @Insert
    suspend fun save(vararg album: Album)

    @Transaction
    @Query("SELECT * FROM artist")
    suspend fun getAll(): List<ArtistAndAlbums>

    @Transaction
    @Query("SELECT * FROM artist WHERE id = :id")
    suspend fun getByArtistId(id: String): ArtistAndAlbums
}

trying this out, (all these operations happens in a Coroutine)

// creating objects
val artist = Artist(id="hillsongunited", name="Hillsong United" )
val artist2 = Artist(id="planetshakers", name="Planet Shakers" )

val album1 = Album(albumId = "empires", name = "Empires", artist = artist.id)
val album2 = Album(albumId = "wonder", name = "Wonder", artist = artist.id)
val album3 = Album(albumId = "people", name = "People", artist = artist.id)

val album4 = Album(albumId = "rain", name = "Rain", artist = artist2.id)
val album5 = Album(albumId = "itschristmas", name = "Its Christmas", artist = artist2.id)
val album6 = Album(albumId = "overitall", name = "Over It All", artist = artist2.id)

// saving to database
SongDatabase.invoke(applicationContext).library().save(artist)
SongDatabase.invoke(applicationContext).library().save(artist2)
SongDatabase.invoke(applicationContext).library().save(album1, album2, album3, album4, album5, album6)

Logging out all Artists

val all = SongDatabase.invoke(applicationContext).library().getAll()
Log.d("debug", "All Artists $all ")

D/debug: All Artists [ArtistAndAlbums(artist=Artist(id=hillsongunited, name=Hillsong United), albums=[Album(albumId=empires, name=Empires, artist=hillsongunited), Album(albumId=wonder, name=Wonder, artist=hillsongunited), Album(albumId=people, name=People, artist=hillsongunited)]), ArtistAndAlbums(artist=Artist(id=planetshakers, name=Planet Shakers), albums=[Album(albumId=rain, name=Rain, artist=planetshakers), Album(albumId=itschristmas, name=Its Christmas, artist=planetshakers), Album(albumId=overitall, name=Over It All, artist=planetshakers)])]

Logging out albums by a specific artist,

val hillsongAlbums = SongDatabase.invoke(applicationContext).library().getByArtistId(artist.id)
Log.d("debug", "Albums by artist ID: $hillsongAlbums ")

D/debug: Albums by artist ID: ArtistAndAlbums(artist=Artist(id=hillsongunited, name=Hillsong United), albums=[Album(albumId=empires, name=Empires, artist=hillsongunited), Album(albumId=wonder, name=Wonder, artist=hillsongunited), Album(albumId=people, name=People, artist=hillsongunited)]) 

Solution 3:

@ForeignKey annotations are not used to define relations when getting data but to define relations when modifying data. To get relational data from a Room databse, Google recommends the @Relation along with the @Embedded annotation.

You can check out my answer here for more explanation if you're interested.