前言
在開發中用到多表一起查詢的時候,我以前都是使用這個方法(Android—Room數據庫多表查詢(Relationships))最近發現谷歌原生room裏竟然有個@Relation註解用來解決這個問題的,用起來還相當方便,故在此記錄一下。
參考鏈接
Relation - Android 開發者
androidx.room.Relation - Android 開發者
代碼
假設一個需求,你有n個朋友,你有n種禮物,你給每個朋友都送了不止一種禮物,最後需要得到一個列表【朋友 + 得到的禮物】
創建兩個數據表
第一個是朋友的表
@Entity(tableName = "friend_table")
data class FriendInfo(
// 唯一
@PrimaryKey(autoGenerate = true)
var friendId: Int = 0,
var friendName: String = ""
) : Serializable
第一個是禮物的表
@Entity(tableName = "gift_table")
data class GiftInfo(
// 唯一
@PrimaryKey(autoGenerate = true)
var giftId: Int = 0,
var giftName: String = "",
var giftLable: String = ""
) : Serializable
創建記錄
再創建一個表來記錄你送給朋友的禮物
@Entity(tableName = "friend_gift_table",
primaryKeys = ["friendId", "giftId"],)
data class FriendGiftRelation(
var friendId: Int = 0,
var giftId: Int = 0,
) : Serializable
創建讀取合併實體類
最後你需要將這種關係一起讀取出來放到一個實體裏
data class FriendWithGiftList (
@Embedded
var friendInfo: FriendInfo,
@Relation(parentColumn = "friendId", // 這個參數來自於FriendInfo的唯一Key
entityColumn = "giftId", // 這個參數來自於GiftInfo的唯一Key
entity = GiftInfo::class,
associateBy = Junction(FriendGiftRelation::class))
var giftList: List<GiftInfo>
) : Serializable
創建Dao
這是讀取邏輯
@Query("SELECT * FROM friend_table")
fun queryAllFriendWithGiftList() : LiveData<List<FriendWithGiftList>>
最後
當然,@Relation註解不是隻能像上面例子那樣使用,還有更多詳細用法,請參考上面的 參考鏈接