Entity
Entity的实例对应的是对象模型数据库中数据表的一行数据,其数据结构自然就是对应着表结构. 而这种映射结构是用注释来标明的.
- 表名 --> 类名
@Entity(tableName = "user")
- 列名 --> 成员变量名
@ColumnInfo(name = "first_name")
- 存储数据类型 --> 成员变量数据类型
var name: String = ""
- 主键
@PrimaryKey(autoGenerate = true)
- 索引
@Entity(indices = {@Index(value = {"first_name", "last_name"}, unique = true)})
- 外键
@Entity(indices = arrayOf(Index(value = *arrayOf("first_name", "last_name"), unique = true)))
class User {
@PrimaryKey
var id: Int = 0
@ColumnInfo(name = "first_name")
var firstName: String? = null
@ColumnInfo(name = "last_name")
var lastName: String? = null
@Ignore
var picture: Bitmap? = null
}
@Entity(foreignKeys = arrayOf(ForeignKey(entity = User::class, parentColumns = arrayOf("id"), childColumns = arrayOf("user_id"))))
class Book {
@PrimaryKey
var bookId: Int = 0
var title: String? = null
@ColumnInfo(name = "user_id")
var userId: Int = 0
}
Dao (Data Access Objects)
Dao 是数据管理层,负责对数据库进行增删改查的操作
你只需要简单地用注解标注,就能自动生成相关的代码了.值得注意的是,这些代码都需要在子线程中运行,所以用其配合Rxjava是再好不过的了
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAll():Flowable<List<User>>
@Insert(onConflict = REPLACE)
fun insert(user: User)
@Update(onConflict = REPLACE)
fun update(user: User)
@Delete
fun delete(user: User)
}
Database
最后,我们来到了Database,它标注了数据库的名称,版本,包含的表.最重要的是,生成Dao的获取方法.
@android.arch.persistence.room.Database(entities = arrayOf(User::class), version = 1)
abstract class Database : RoomDatabase() {
abstract fun userDao(): UserDao
}
当然,我们还需要一个单例来让我们获取这个数据库的实例,如下
class DataBaseHelper private constructor() {
companion object {
val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
DataBaseHelper()
}
}
var database: Database? = null
fun setup(context: Context) {
database = Room.databaseBuilder(context.applicationContext, Database::class.java, "database.sqlite")
.build()
}
}