1). 简介
Room persistence库为SQLite提供了一个抽象层,以便在利用SQLite的全部功能的同时实现更强大的数据库访问。
该库可帮助您在运行应用程序的设备上创建应用程序数据的缓存。 此缓存作为应用程序的唯一事实来源,允许用户在应用程序中查看关键信息的一致副本,无论用户是否具有Internet连接。
2). 依赖
buildscript {
ext.room_version = "1.1.0"
}
dependencies {
// Room 使用
implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
// optional - RxJava support for Room
implementation "android.arch.persistence.room:rxjava2:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "android.arch.persistence.room:guava:$room_version"
// Test helpers
testImplementation "android.arch.persistence.room:testing:$room_version"
// Kotlin
kapt "android.arch.persistence.room:compiler:$room_version"
}
3). 数据实体类
* 实体类
* Created by mazaiting on 2018/7/25.
*/
@Entity
data class User(
@PrimaryKey
val uid: Int,
@ColumnInfo(name = "first_name")
var firstName: String,
@ColumnInfo(name = "last_name")
var lastName: String
)
4). 用户DAO类
/**
* 用户DAO类
* Created by mazaiting on 2018/7/25.
*/
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAll(): List<User>
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List<User>
@Query("SELECT * FROM user WHERE first_name LIKE :first AND last_name LIKE :last LIMIT 1")
fun findByName(first: String, last: String): User
@Insert
fun insertAll(users: List<User>)
// 可变参数
// fun insertAll(vararg users: User)
@Delete
fun delete(user: User)
@Update
fun update(user: User)
}
5). 数据库类
/**
* 数据库类
* Created by mazaiting on 2018/7/25.
*/
@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
// 获取DAO
abstract fun userDao(): UserDao
}
6). 创建数据库
btn_create_db.setOnClickListener {
val db = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "TEST").build()
userDao = db.userDao()
}
7). 新增数据
对数据的操作必须在子线程中
btn_insert.setOnClickListener {
Thread(Runnable {
val users = (0..10).map { User(it, "first$it", "last$it") }
userDao.insertAll(users)
}).start()
}
8). 查询数据
btn_find_all.setOnClickListener {
Thread(Runnable {
userDao.getAll().forEach { L.e(it.toString()) }
}).start()
}
btn_find_id.setOnClickListener {
Thread(Runnable {
userDao.loadAllByIds(intArrayOf(0, 1, 2, 3, 4)).forEach { L.e(it.toString()) }
}).start()
}
btn_find_name.setOnClickListener {
Thread(Runnable {
L.e(userDao.findByName("first1", "last1").toString())
}).start()
}
9). 更新数据
btn_update.setOnClickListener {
Thread(Runnable {
val user = userDao.findByName("first1", "last1")
user.firstName = "ma"
user.lastName = "zaiting"
userDao.update(user)
userDao.loadAllByIds(intArrayOf(1)).forEach { L.e(it.toString()) }
}).start()
}
10). 删除数据
btn_delete.setOnClickListener {
Thread(Runnable {
userDao.delete(userDao.loadAllByIds(intArrayOf(0))[0])
}).start()
}