Jetpack之数据库——Room

强颜欢笑 提交于 2020-01-18 18:21:22

Room是Jetpack提供的数据库框架,支持kotlin语言,支持Rxjava调用方式。

Room使用

  1. 添加依赖
    dependencies {
          def room_version = "2.2.2"
          implementation "androidx.room:room-runtime:$room_version"
          // For Kotlin use kapt instead of annotationProcessor
          annotationProcessor "androidx.room:room-compiler:$room_version" 
        }
    
  2. 定义数据表对应的实体类
    @Entity(tableName = "videoUpload")
    public class VideoUploadDBModel implements Serializable {
        @NonNull
        @PrimaryKey
        public String uuid;
        public String path;
        public Long size;
        public Integer status;
        public String userId;
    }
    
    必须要加@Entity注解
  3. 定义数据表操作类
    @Dao
    interface VideoUploadDao {
        @Insert(onConflict = OnConflictStrategy.REPLACE)
        fun insert(videoUploadDBModel: VideoUploadDBModel)
    
        @Update(onConflict = OnConflictStrategy.REPLACE)
        fun update(videoUploadDBModel: VideoUploadDBModel)
    
        @Query("select * from videoUpload where uuid==:uuid")
        fun query(uuid: String): List<VideoUploadDBModel>
    
        @Query("select * from videoUpload")
        fun queryAll(): List<VideoUploadDBModel>
    
        @Query("delete from videoUpload where uuid==:uuid")
        fun delete(uuid: String)
    }
    
  4. 定义数据库类
    	@Database(entities = [VideoUploadDBModel::class], version = 1)
    	abstract class VideoDatabase : RoomDatabase() {
    	    abstract fun videoUploadDao(): VideoUploadDao
    	}
    
  5. 使用
    val database = Room.databaseBuilder(mContext, VideoDatabase::class.java, "fcat.db").build()
    val videoUploadList = database.videoUploadDao().queryAll()
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!