Android Room

325 阅读1分钟

1.配置

apply plugin: 'kotlin-kapt'
------------------------------------------------------------------------------
implementation 'androidx.room:room-runtime:2.2.4'
kapt 'androidx.room:room-compiler:2.2.4'

2.设计Student表

@Entity
data class Student(
    @PrimaryKey(autoGenerate = true) var id: Int,
    var name: String,
    var age: Int,
    var sex: String = "male",
    var hello: String = "hello",
    var nihao: String = "nihao",
    var hao: String = "hao"
)

3.定义dao

@Dao
interface StudentDao {
    //id 从1开始,delete根据主键id
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(list: MutableList<Student?>?)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(vararg student: Student)

    @Delete
    fun delete(vararg student: Student)

    @Delete
    fun deleteall(list: MutableList<Student?>?)

    @Query("SELECT * FROM Student")
    fun findall(): MutableList<Student?>?

    @Query("SELECT * FROM student WHERE id = :id")
    fun findbyId(id: Int): Student

    @Query("SELECT * FROM student WHERE name = :name")
    fun findbyname(name: String): MutableList<Student?>?
}

4.MyDatabase

@Database(entities = [Student::class], version = 7)
abstract class MyDatabase : RoomDatabase() {
    abstract fun studentDao(): StudentDao

    //这里是TEXT,而非varchar,sqlite不支持drop,rename
    companion object {
        private val MIGRATION_6_7: Migration by lazy {
            object : Migration(6, 7) {
                override fun migrate(database: SupportSQLiteDatabase) {
                    database.execSQL(
                        "ALTER TABLE Student add COLUMN hao text not null default 'hao' "
                    )
                }
            }
        }
        val db by lazy {
            Room.databaseBuilder(
                App.context!!,
                MyDatabase::class.java,
                "my.db"
            )
                //不合并数据,升级后清空数据
//                .fallbackToDestructiveMigration()
                //升级后合并数据
                .addMigrations(MIGRATION_6_7)
                .build()
        }
    }

}

5.App

class App : Application() {
    override fun onCreate() {
        super.onCreate()
        instance = this
        context = applicationContext
    }

    companion object {
        @JvmStatic
        var instance: App? = null
            private set
        var context: Context? = null
            private set
    }

}

6.使用

class RoomActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room)

        button11.setOnClickListener {
            val values1 = Student(1, "", 0)
            val values2 = Student(2, "John Smith2", 21)
            val values3 = Student(3, "John Smith3", 21)
            val db = MyDatabase.db

            thread {
                //                db.studentDao().insertAll(mutableListOf(values1,values2,values3))
                val all = db.studentDao().findall()
                runOnUiThread {
                    textView2.text = all.toString()
                }
            }

        }
    }
}