Room数据库的使用

Author Avatar
weechan 3月 25, 2018

Room

标签(空格分隔): 未分类


Gradle配置

1
2
3
4

implementation "android.arch.persistence.room:rxjava2:1.0.0"
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"

Room数据库的简单例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//实体类,每个字段都是数据库中的一列
@Entity(tableName = "article")
data class ArticleDetial(
@PrimaryKey(autoGenerate = true)
val id : Int,
val author: String,
val title: String,
val content: String)

//Dao接口 操作数据库的主要接口
@Dao
interface ArticleDao {

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertArticle(article : ArticleDetial)

@Delete()
fun deleteArticle(article:ArticleDetial)

@Query("DELETE FROM article")
fun deleteAllArticles()

@Query("SELECT * FROM article ORDER BY id DESC")
fun queryArticle(): Single<List<ArticleDetial>>

@Query("SELECT * FROM article WHERE id IN (:range)")
fun queryRange(range:IntArray):Flowable<List<ArticleDetial>>
}

//数据库S,为应用创建数据库
@Database(entities = {ArticleDetial.class},version=1)
public abstract class AppDatabase extends RoomDatabase{
public abstract ArticleDao articleDao();
}


val db : AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "articles").build()
创建数据库

各个注解的参数参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@PrimaryKey 主键
autoGenerate 自增

@ColumnInfo
name 重命名列名

@Insert 插入方法
@Update
onConflict 冲突策略 //https://sqlite.org/lang_conflict.html

int ABORT
OnConflict strategy constant to abort the transaction.

int FAIL
OnConflict strategy constant to fail the transaction.

int IGNORE
OnConflict strategy constant to ignore the conflict.

int REPLACE
OnConflict strategy constant to replace the old data and continue the transaction.

int ROLLBACK
OnConflict strategy constant to rollback the transaction.

@Delete 删除

@Query查询
value SQLITE语句