引入依赖
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
在android 配置中加入
apply plugin: 'kotlin-kapt' //kapt
android{
... defaultConfig{
... //指定room.schemaLocation生成的文件路径 javaCompileOptions { annotationProcessorOptions { arguments = ["room.schemaLocation": "$projectDir/schemas".toString()] } } } ... }
定义相应的实体类
@Entity(tableName = "t_user") class User { @PrimaryKey @NonNull var id: String = "" var username: String? = null var name: String? = null var sex: Int? = null var pic: String? = null var area: String? = null var phone: String? = null var address: String? = null var disabled: Boolean? = null var delFlag: Boolean? = null }
字符串主键 一定要添加 @NonNull 注解
下面就是dao了
@Dao interface UserDao { @Query("select * from t_user where id=:id limit 1") fun get(id:String): User? @Query("select * from t_user where delFlag = false") fun query():List<User> //插入或更新 @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertOrUpdate(user: User) @Query("delete from t_user where id=:id") fun delete(id: String) }
然后就是database类
@Database(entities = [User::class, 其他定义的数据类...],version = 1,exportSchema = true) @TypeConverters(DateConverter::class, BoolConverter::class) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao ... }
@TypeConverters 这里使用了两个自定义的转换器 处理
1.数字转boolean
class BoolConverter { @TypeConverter fun revertDate(value: Number): Boolean { return value == 1 } @TypeConverter fun converterDate(value: Boolean): Number { return if(value) 1 else 0 } }
2.毫秒数转日期
class DateConverter { @TypeConverter fun revertDate(value: Long): Date { return Date(value) } @TypeConverter fun converterDate(value: Date): Long { return value.time } }
然后定义一个database帮助类
object AppDatabaseHelper { private var appDatabase: AppDatabase init { //MyApp 是自定义application类 val appContext = MyApp.instance.applicationContext appDatabase = Room.databaseBuilder(appContext, AppDatabase::class.java,"mydb") .allowMainThreadQueries() .fallbackToDestructiveMigration() //升级数据库版本 清空数据库 //.addMigrations(MIGRATION_1_2,...) 可以自己定制数据库迁移 .build() // 比如1版本升级2版本 消息表增加了一个字段msgId // val MIGRATION_1_2 = object :Migration(1,2){ // override fun migrate(database: SupportSQLiteDatabase) { // database.execSQL("ALTER TABLE t_msg " // + " ADD COLUMN msgId TEXT"); // } // } } fun getInstance(): AppDatabase { return appDatabase } }
最后是使用
private val userDao = AppDatabaseHelper.getInstance().userDao() //调用dao的各种方法就可以使用了 //需要注意,不能再主线程使用