Room是Jetpack提供的数据库框架,支持kotlin语言,支持Rxjava调用方式。
Room使用
- 添加依赖
dependencies {def room_version = "2.2.2"implementation "androidx.room:room-runtime:$room_version"// For Kotlin use kapt instead of annotationProcessorannotationProcessor "androidx.room:room-compiler:$room_version" }
- 定义数据表对应的实体类
必须要加@Entity注解@Entity(tableName = "videoUpload") public class VideoUploadDBModel implements Serializable {@NonNull@PrimaryKeypublic String uuid;public String path;public Long size;public Integer status;public String userId; }
- 定义数据表操作类
@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) }
- 定义数据库类
@Database(entities = [VideoUploadDBModel::class], version = 1)abstract class VideoDatabase : RoomDatabase() {abstract fun videoUploadDao(): VideoUploadDao}
- 使用
val database = Room.databaseBuilder(mContext, VideoDatabase::class.java, "fcat.db").build() val videoUploadList = database.videoUploadDao().queryAll()