如何在Room持久性库中使用外键

时间:2017-11-27 13:08:39

标签: android android-room

我在android中使用房间持久性库,如果有人可以帮我使用外键,如何使用外键获取数据,我将不胜感激。

4 个答案:

答案 0 :(得分:14)

此处介绍了如何在 Android Jetpack Room 中定义和访问一对多 (Foreign Key) 关系。这里的实体是 ArtistAlbum,外键是 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
)

然后是嵌入对象 (read official Android documentation: Define relationships between objects)

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

最后是 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
}

尝试一下,(所有这些操作都发生在协程中)

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

退出所有艺术家

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

退出特定艺术家的专辑,

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

答案 1 :(得分:4)

我使用了一个不错的教程:

  

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

还提供了有关以下信息:@embeded, @ignore,@ColumnInfo

当我们使用外键时,不要忘记以这种方式放置onDelete = ForeignKey.CASCADE,如果您删除数据,它也会删除依赖关系。这样,您就不会有虚假数据或从未使用过的数据

答案 2 :(得分:1)

仅总结以上文章以供将来的读者使用

Kotlin中的外键语法为

@Entity(foreignKeys = arrayOf(ForeignKey(entity = ParentClass::class,
                    parentColumns = arrayOf("parentClassColumn"),
                    childColumns = arrayOf("childClassColumn"),
                    onDelete = ForeignKey.CASCADE)))

Java中的外键语法为:

@Entity(foreignKeys = @ForeignKey(entity = ParentClass.class,
    parentColumns = "parentClassColumn",
    childColumns = "childClassColumn",
    onDelete = ForeignKey.CASCADE))

有关更多信息,请参阅官方文档。 https://developer.android.com/reference/android/arch/persistence/room/ForeignKey.html

答案 3 :(得分:0)

@ForeignKey 注释不是用来在获取数据时定义关系,而是在修改时定义关系em> 数据。从一个室DATABSE得到的关系数据,谷歌建议@Relation连同@Embedded注解

如果您有兴趣,可以查看my answer here以获得更多解释。