简介
Room持久库提供了一个SQLite抽象层,让你访问数据库更加稳如狗,提示数据库性能。
Room库帮助应用数据缓存,这个缓存是应用唯一的真实来源,并且允许用户查看应用中的关键信息的一致副本。
导入库
dependencies {
def room_version = "1.1.1"
implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version" // use kapt for Kotlin
// 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"
}
在Androidx版本下
dependencies {
def room_version = "2.0.0-beta01"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version" // use kapt for Kotlin
// optional - RxJava support for Room
implementation "androidx.room:room-rxjava2:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// Test helpers
testImplementation "androidx.room:room-testing:$room_version"
}
ROOM的三个重要组件
Database具体可看官网,用@Database注解的类应该需要满足以下条件
- 一个继承RoomDatabase的抽象类
- 在注释中包含数据库相关联的实体列表
- 在包含具有0个参数的抽象方法,并返回用@Dao
在运行时,可以通过调用Room.databaseBuild()或者Room.inMemoryDatabaseBuild()
获取数据库实例
Entity:表示数据库内的表
Dao:包含用于访问数据库的方法。
这些组件,以及它们与程序的其余部分的关系可自寻在网上找图图解.
下面代码示例包含了entity与dao数据的配置
kotlin写法
@Entity
data class User(
var userName: String,
var passWord: String
) {
@PrimaryKey
var id = 0
}
Java写法,参考
@Entity
public class User {
@PrimaryKey
private int uid;
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "last_name")
private String lastName;
// Getters and setters are ignored for brevity,
// but they're required for Room to work.
}
userDao.kt
@Dao
interface UserDao {
//查询user表中所有数据
@get:Query("SELECT * FROM user")
val all: List<User?>?
@Query("SELECT * FROM user WHERE 'uid' IN (:userIds)")
fun loadAllByIds(userIds: IntArray?): List<User?>?
// @Query("SELECT * FROM user LIMIT 1")
// void findUser(User user);
@Query("SELECT * FROM User LIMIT 1")
fun findUser(): User?
@Insert
fun insertAll(users: User?)
@Delete
fun delete(vararg users: User?)
@Query("DELETE FROM User")
fun deleteAllUser()
}
userDao.java
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);
@Query("SELECT * FROM user WHERE first_name LIKE :first AND "
+ "last_name LIKE :last LIMIT 1")
User findByName(String first, String last);
@Insert
void insertAll(User... users);
@Delete
void delete(User user);
}
AppDatabase .kt
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao?
}
AppDatabase.java
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
在创建上面的文件之后,使用以下代码获得创建数据库的实例:
kotlin
var db: AppDatabase? = null
db = Room.databaseBuilder(applicationContext,
AppDatabase::class.java, "database-name")
.allowMainThreadQueries() //允许在主线程中查询
.build()
java
AppDatabase db;
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name")
.allowMainThreadQueries()//允许在主线程中查询
.build();
注意:在实例化AppDatabase对象时,应遵循单例设计模式,因为每个Roomdatabase实例都相当消耗性能,并且您很少需要访问多个实例。
参考文章:https://blog.csdn.net/u011897062/article/details/82107709本人增加了kontlin写法