android_Room数据库中的一对多关系
先看一遍 带有翻译的官方的Room数据库讲解 看完官方小姐姐的讲解的在看下面的就简单了很多
主要的点就是一定要有关联键 关联键的值一定要一样 其他的就没有啥重要的了基本都是CURD(如果你不了解Room的基础,请先去看看基础用法)最后有DEMO
1、开始创建Entity
1、创建一个人的实体
import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Owner( val name: String ) { //关联键 @PrimaryKey var ownerId: Long = 2 }
2、创建一个狗狗类用于对应
@Entity data class Dog( val name: String, val cuteness: Int, val barkVolume: Int, val breed: String ) { @PrimaryKey(autoGenerate = true) var dogId: Long=0 //这个变量在后面类中可以看到(关联键) var dogOwnerId: Long=2 }
3、又创建了一个Cat类
import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Cat( val catName: String ) { @PrimaryKey(autoGenerate = true) var catId: Long = 0 //关联键 var catOwnerId: Long=2 }
2、创建Dao
按照上面的三个依次创建了3个Dao(我只是创建了添加的方法)
3、关键的来了
//人的dao @Dao interface OwnerDao { @Insert fun insert(owner: Owner) } //Cat的dao层 @Dao interface CatDao { @Insert fun insert(cat: Cat) } //Dog的dao层 @Dao interface DogDao { @Insert fun insert(dogDao: Dog) }
创建一个Entity把Dog、Cat、Owner链接起来的类
import androidx.room.Embedded import androidx.room.Relation data class OwnerWithDogs( @Embedded val owner: Owner, @Relation( parentColumn = "ownerId",//关联键 entityColumn = "dogOwnerId"//关联键 ) val dogs: List<Dog>, @Relation( parentColumn = "ownerId",//关联键 entityColumn = "catOwnerId"//关联键 ) val cats: List<Cat> )
创建Dao
import androidx.room.Dao import androidx.room.Query import androidx.room.Transaction import com.example.myroomtest.room.entity.OwnerWithDogs import io.reactivex.Single @Dao interface DogsAndOwnersDao { @Transaction @Query("SELECT * FROM Owner")//SQ写的是查询主键的类(也就是那个人Owner类) fun getDogsAndOwners(): Single<List<OwnerWithDogs>> //在接受结果的时候使用的OwnerWithDogs关联类接收 }
创建数据库的初始类(简单自己封装的)
object DBInstance { // private static final String DB_NAME = "/sdcard/LianSou/room_test.db"; private val DB_NAME = "test.db" var appDataBase: MyDataBase? = null fun getInstance(): MyDataBase? { if (appDataBase == null) { synchronized(DBInstance::class.java) { if (appDataBase == null) { appDataBase = Room.databaseBuilder( FinancialExchangeApplication.context, MyDataBase::class.java, DB_NAME ) //不推荐打开这句,但是为了demo展示,我只能打开了 .allowMainThreadQueries() .build() } } } return appDataBase } }
自己封装了一个dao层的工具类
@Database( entities = [Owner::class, Dog::class, Cat::class], version = 1, exportSchema = false ) abstract class MyDataBase : RoomDatabase() { abstract fun getDao(): DogsAndOwnersDao abstract fun getDog(): DogDao abstract fun getOwen(): OwnerDao abstract fun getCat(): CatDao }
引入依赖
//Room的依赖引用 implementation "androidx.room:room-runtime:2.2.5" implementation "androidx.room:room-ktx:2.2.5" kapt "androidx.room:room-compiler:2.2.5" androidTestImplementation "androidx.room:room-testing:2.2.5" implementation "androidx.room:room-rxjava2:2.2.5" //room的RxJ implementation "io.reactivex.rxjava2:rxandroid:2.1.0" //线程调度器
就是这样完事了
附上Git(Demo)的地址