美文网首页
Jetpack之Room使用

Jetpack之Room使用

作者: wasdzy111 | 来源:发表于2021-03-19 16:44 被阅读0次

    1、引包

        implementation 'androidx.room:room-runtime:2.2.5'
        implementation 'androidx.room:room-common:2.2.5'
    

    2、编写bean

    /**
     * user 实体类定义
     *  indices = [Index(value = ["name"], unique = true)]  = name 唯一约束
     */
    @Entity(indices = [Index(value = ["name"], unique = true)])
    class User() {
        //自增长主键
        @PrimaryKey(autoGenerate = true)
        var autoId: Int = 0
    
        @ColumnInfo(name = "name")
        var name: String? = null
        var nickName: String? = null
        var age: Int? = null
    }
    

    3、Dao类

    /**
     * user 对应的dao类
     */
    @Dao
    public interface UserDao {
        /**
         * 插入user对象
         * @param user Array<out User> 一个user或者多个user
         */
        @Insert(onConflict = OnConflictStrategy.REPLACE)//有了就替换
        fun insertAll(vararg user: User)
    
        /**
         * 删除user对象
         */
        @Delete
        fun delete(vararg user: User)
    
        @Update
        fun updates(vararg user: User)
    
        /**
         * 查找所有
         * @return List<User>
         */
        @Query("select * from user")
        fun loadAll(): List<User>
    
        /**
         * 根据用户名查找用户
         * @param name String
         * @return User?
         */
        @Query("select * from user where name = :name ")
        fun findByName(name: String): User
    }
    

    4、数据库抽象类

    /**
     * 定义了数据库中数据表  版本号
     */
    @Database(entities = [User::class], version = 2)
    public abstract class AppDataBase : RoomDatabase() {
        abstract fun userDao(): UserDao
    }
    

    5、数据库管理工具

    object AppDataBaseHelper {
        private val databseName: String = "mydatabase"
        private var dataBase: AppDataBase? = null
            private get() {
                return field
            }
            private set
    
        public fun getDB(): AppDataBase {
            if (null == dataBase) {
                throw RuntimeException("请先init database")
            }
            return dataBase!!
        }
    
        fun initDb(application: Application) {
            dataBase = Room.databaseBuilder(
                application,
                AppDataBase::class.java,
                databseName)
                //.addMigrations() 添加升级规则
                .allowMainThreadQueries()
                .build()
        }
    
        //升级规则
        val MIGRATION_1_2: Migration = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "CREATE TABLE `Fruit` (`id` INTEGER, "
                            + "`name` TEXT, PRIMARY KEY(`id`))"
                )
            }
        }
    
        val MIGRATION_2_3: Migration = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    ("ALTER TABLE Book "
                            + " ADD COLUMN pub_year INTEGER")
                )
            }
        }
    }
    

    6、测试用

    class RoomActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_room)
            var u = User()
            u.name = "张三测试2"
            u.age = 19
            u.nickName = "abu"
            GlobalScope.launch(Dispatchers.IO) {
                AppDataBaseHelper.initDb(application)
                AppDataBaseHelper.getDB().userDao().insertAll(u)
                val userList = AppDataBaseHelper.getDB().userDao().loadAll()
                withContext(Dispatchers.Main) {
                    userList.forEach {
                        println(Gson().toJson(it))
                    }
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Jetpack之Room使用

          本文链接:https://www.haomeiwen.com/subject/hcxbcltx.html