Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 881
Nirmal Prajapat Avatar asked Nov 27 '17 13:11

Nirmal Prajapat


People also ask

What is foreign key room android?

android.arch.persistence.room.ForeignKey. Declares a foreign key on another Entity . Foreign keys allows you to specify constraints across Entities such that SQLite will ensure that the relationship is valid when you modify the database.

Where the foreign key should be stored?

When you join the two tables together, the primary key of the parent table will be set equal to the foreign key of the child table. Whichever one is not the primary key is the foreign key. In one-to-many relationships, the FK goes on the "many" side.

How are foreign keys stored?

Foreign key references are stored within a child table and links up to a primary key in a separate table. The column acting as a foreign key must have a corresponding value in its linked table.

What is a foreign key column?

A foreign key is a column (or combination of columns) in a table whose values must match values of a column in some other table. FOREIGN KEY constraints enforce referential integrity, which essentially says that if column value A refers to column value B, then column value B must exist.


2 Answers

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

like image 55
rmutalik Avatar answered Sep 27 '22 00:09

rmutalik


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)])  
like image 23
All Іѕ Vаиітy Avatar answered Sep 23 '22 00:09

All Іѕ Vаиітy