2.Entity:代表一个表结构。
3.Dao:数据访问对象是Room的主要组件,负责定义访问数据库的方法。
声明依赖项
def room_version = “2.3.0”
implementation “androidx.room:room-runtime:$room_version”
annotationProcessor “androidx.room:room-compiler:$room_version”
配置编译器解释
1.“room.schemaLocation”:"$projectDir/schemas".toString(),的作用是将配置并启把据库架构导出json文件到指定目录
2.“room.incremental”:“true”:Gradle 增量注解处理器
3.“room.expandProjection”:“true”:配置 Room 以重写查询,使其顶部星形投影在展开后仅包含 DAO 方法返回类型中定义的列。
//配置编译器代码
android {
…
defaultConfig {
…
javaCompileOptions {
annotationProcessorOptions {
arguments += [
“room.schemaLocation”:"$projectDir/schemas".toString(),
“room.incremental”:“true”,
“room.expandProjection”:“true”]
}
}
}
}
创建图书表
@Entity(tableName = “book”)
class Book {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@ColumnInfo(name = “bookname”)
var name: String? = “”
constructor(bookname: String?) {
this.name = bookname
}
}
表注解解释
1.如果想给一个表设置表名就在@Entity的后面添加(tableName = “book”),不是设置默认采用类名
2.声明表的主键 @PrimaryKey(autoGenerate = true)
3.更改表的属性列名@ColumnInfo(name = “bookname”),默认类的字段名
1.定义Dao类
@Dao
interface BookDao {
@Insert
fun addBook(book : Book)
@Query(“SELECT * FROM book”)
fun loadAll(): List
@Query(“select * from book where name = :name”)
fun queryName(name : String) :List
@Delete
fun delete(song: Book?)
}
如果在query时返回值类型和查询的表名和返回值类型或查询的表名不相同时,在程序编译会编译失败,这也降低了
程序在运行时出现的风险
2.定义数据库和生成数据类
@Database(entities = [Book::class], version = 1)
abstract class RoomDaoManager : RoomDatabase() {
abstract fun BookDao(): BookDao
companion object {
private val DATABASE_NAME = “dev_db.db”
private var databaseInstance: RoomDaoManager? = null
@Synchronized
open fun getInstance(): RoomDaoManager? {
if (databaseInstance == null) {
databaseInstance = Room
.databaseBuilder(
MyApplication.instance(),
RoomDaoManager::class.java,
DATABASE_NAME
)
.allowMainThreadQueries()
.build()
}
return databaseInstance
}
}
}
databaseInstance = Room
.databaseBuilder(
MyApplication.instance(),
RoomDaoManager::class.java,
DATABASE_NAME
)
.allowMainThreadQueries()
.build()
}
return databaseInstance
}
}
}