其他
Room 中的数据库关系
Room 2.2
https://developer.android.google.cn/jetpack/androidx/releases/room#version_220_3
@Relation
https://developer.android.google.cn/reference/android/arch/persistence/room/Relation
一对一关系
一对一关系
@Entity
data class Dog(
@PrimaryKey val dogId: Long,
val dogOwnerId: Long,
val name: String,
val cuteness: Int,
val barkVolume: Int,
val breed: String
)
@Entity
data class Owner(@PrimaryKey val ownerId: Long, val name: String)
data class DogAndOwner(
val owner: Owner,
val dog: Dog
)
SELECT * FROM Owner
SELECT * FROM Dog WHERE dogOwnerId IN (ownerId1, ownerId2, …)
data class DogAndOwner(
@Embedded val owner: Owner,
@Relation(
parentColumn = "ownerId",
entityColumn = "dogOwnerId"
)
val dog: Dog
)
@Transaction
@Query("SELECT * FROM Owner")
fun getDogsAndOwners(): List<DogAndOwner>
Dao https://developer.android.google.cn/reference/androidx/room/Dao @Transaction https://developer.android.google.cn/reference/androidx/room/Transaction.html
一对多关系
data class OwnerWithDogs(
val owner: Owner,
val dogs: List<Dog>
)
data class OwnerWithDogs(
@Embedded val owner: Owner,
@Relation(
parentColumn = "ownerId",
entityColumn = "dogOwnerId"
)
val dogs: List<Dog>
)
@Transaction
@Query("SELECT * FROM Owner")
fun getDogsAndOwners(): List<OwnerWithDogs>
多对多关系
多对多关系
@Entity(primaryKeys = ["dogId", "ownerId"])
data class DogOwnerCrossRef(
val dogId: Long,
val ownerId: Long
)
associative
https://en.wikipedia.org/wiki/Associative_entity
SELECT * FROM Owner
SELECT
Dog.dogId AS dogId,
Dog.dogOwnerId AS dogOwnerId,
Dog.name AS name,
_junction.ownerId
FROM
DogOwnerCrossRef AS _junction
INNER JOIN Dog ON (_junction.dogId = Dog.dogId)
WHERE _junction.ownerId IN (ownerId1, ownerId2, …)
data class OwnerWithDogs(
@Embedded val owner: Owner,
@Relation(
parentColumn = "ownerId",
entityColumn = "dogId",
associateBy = Junction(DogOwnerCrossRef::class)
)
val dogs: List<Dog>
)
Junction
https://developer.android.google.cn/reference/androidx/room/Junction
在我们的 Dao 中,我们需要从 Owners 中选择并返回正确的数据类:
@Transaction
@Query("SELECT * FROM Owner")
fun getOwnersWithDogs(): List<OwnerWithDogs>
更高阶的数据库关系用例
data class Pup(
val name: String,
val cuteness: Int = 11
)
data class OwnerWithPups(
@Embedded val owner: Owner,
@Relation(
parentColumn = "ownerId",
entity = Dog::class,
entityColumn = "dogOwnerId"
)
val dogs: List<Pup>
)
data class OwnerWithDogs(
@Embedded val owner: Owner,
@Relation(
parentColumn = "ownerId",
entity = Dog::class,
entityColumn = "dogOwnerId",
projection = ["name"]
)
val dogNames: List<String>
)
ForeignKey https://developer.android.google.cn/reference/androidx/room/ForeignKey.html SQLite 中的外键 https://sqlite.org/foreignkeys.html
@Relation https://developer.android.google.cn/reference/androidx/room/Relation.html Room 2.2 的更多新功能 https://developer.android.google.cn/jetpack/androidx/releases/room#version_220_3
想了解更多 Android 内容?
在公众号首页发送关键词 "Android",获取相关历史技术文章;
在公众号首页发送关键词 "ADS",获取开发者峰会演讲中文字幕视频;
还有更多疑惑?欢迎点击菜单 "联系我们" 反馈您在开发过程中遇到的问题。
推荐阅读