美文网首页
Jetpack_Room

Jetpack_Room

作者: 老北瓜 | 来源:发表于2020-03-25 11:09 被阅读0次

    可以快速流畅的访问 Sqlite 数据库
    查看jetpack 官方文档,导入依赖

    dependencies {
          def room_version = "2.2.3"
    
          implementation "androidx.room:room-runtime:$room_version"
          annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor
    
          // optional - Kotlin Extensions and Coroutines support for Room
          implementation "androidx.room:room-ktx:$room_version"
    
          // optional - RxJava support for Room
          implementation "androidx.room:room-rxjava2:$room_version"
    
          // optional - Guava support for Room, including Optional and ListenableFuture
          implementation "androidx.room:room-guava:$room_version"
    
          // Test helpers
          testImplementation "androidx.room:room-testing:$room_version"
        }
    

    涉及到 三个 类 Entity , Dao, Database
    Entity 类

    @Entity
    public class Word {
    
        @PrimaryKey(autoGenerate = true)
        private int id;
    
        private String name;
        private int age;
        
        public Word(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    

    Dao 类

    @Dao
    public interface WordDao {
        @Insert
        void insert(Word... words);
    
       @Query("SELECT * FROM WORD")
       List<Word> queryAll();
    
        /**
         * 全部删除  
         *
         * @Query("DELETE FROM WORD")
         */
        @Delete()
        void deleteAll(List<Word> list);
    
        @Delete
        void delete(Word... word);
    
        @Update
        void update(Word... word);
    }
    

    Database 类

    @Database(entities = Word.class, version = 1, exportSchema = false)
    public abstract class WordDatabase extends RoomDatabase {
        abstract WordDao getWordDao();
    }
    

    在 Activity中的使用

    testDataBase = Room.databaseBuilder(this, WordDatabase.class, "test")
                    .allowMainThreadQueries()
                    .build();
    testDao = testDataBase.getWordDao();
              // 插入
    Word bean = new Word("张三", 21);
    Word bean2 = new Word("李四", 24);
    testDao.insert(bean, bean2);
              
              ...
    

    最基础的使用如上
    升级版 引入LiveData,AsyncTask ,ViewModel , 在ViewModel 中再使用Repository将数据库操作封装。
    WordRepository

    package com.bg.ppjoke.db;
    
    import android.content.Context;
    import android.os.AsyncTask;
    
    import androidx.lifecycle.LiveData;
    
    import java.util.List;
    
    /**
     * 单独操作数据库
     */
    public class WordRepository {
    
        private static WordDao wordDao;
    
        private LiveData<List<Word>> allWords;
    
        public WordRepository(Context context) {
            WordDatabase database = WordDatabase.getInstance(context.getApplicationContext());
            wordDao = database.getWordDao();
            allWords = wordDao.queryAllWords();
        }
    
        public LiveData<List<Word>> getAllWords() {
            return allWords;
        }
    
        void insert(Word... words) {
            new InsertAsyncTask().execute(words);
        }
    
    
        void deleteAll() {
            new DeleteAllAsyncTask().execute();
        }
    
        void delete(Word... words) {
            new DeleteAsyncTask().execute(words);
        }
    
    
        void update(Word... words) {
            new UpdateAsyncTask().execute(words);
        }
    
    
        /**
         * 插入任务 ;
         */
        static class InsertAsyncTask extends AsyncTask<Word, Void, Void> {
    
            @Override
            protected Void doInBackground(Word... words) {
                wordDao.insert(words);
                return null;
            }
        }
    
    
        /**
         * 全部删除 任务 ;
         */
        static class DeleteAllAsyncTask extends AsyncTask<Void, Void, Void> {
            @Override
            protected Void doInBackground(Void... voids) {
                wordDao.deleteAll();
                return null;
            }
        }
    
    
        /**
         * 更新
         */
        static class DeleteAsyncTask extends AsyncTask<Word, Void, Void> {
    
            @Override
            protected Void doInBackground(Word... words) {
                wordDao.delete(words);
                return null;
            }
        }
    
        /**
         * 更新
         */
        static class UpdateAsyncTask extends AsyncTask<Word, Void, Void> {
            @Override
            protected Void doInBackground(Word... words) {
                wordDao.update(words);
                return null;
            }
        }
    }
    

    WordDatabase 实现单例

    @Database(entities = Word.class, version = 1, exportSchema = false)
    public abstract class WordDatabase extends RoomDatabase {
    
        // 这里不能有,有了编译报错
    //    private WordDatabase() {
    //    }
    
        private static WordDatabase INSTANCE = null;
    
        public static WordDatabase getInstance(Context context) {
    
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(), WordDatabase.class, "test_databse")
                        .build();
            }
    
            return INSTANCE;
        }
    
       public abstract WordDao getWordDao();
    }
    

    ViewModel

    public class DbViewModel extends AndroidViewModel {
        private LiveData<List<Word>> allWords;
        private WordRepository repository;
    
        public DbViewModel(@NonNull Application application) {
            super(application);
    
            repository = new WordRepository(application);
            allWords = repository.getAllWords();
        }
    
        public LiveData<List<Word>> getAllWords() {
            return allWords;
        }
    
        void insert(Word... words) {
            repository.insert(words);
        }
    
    
        void deleteAll() {
            repository.deleteAll();
        }
    
        void delete(Word... words) {
            repository.delete(words);
        }
    
    
        void update(Word... words) {
            repository.update(words);
        }
    }
    

    版本迁移 Migration
    暴力行为 ,不保留原来数据, 或者直接卸载app

     if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(), WordDatabase.class, "test_databse")
                        .fallbackToDestructiveMigration()
                        .build();
            }
    

    如果要保留原有数据

     public static WordDatabase getInstance(Context context) {
    
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(), WordDatabase.class, "test_databse")
    //                    .fallbackToDestructiveMigration()
                        .addMigrations(MIGRATION_1_2)
                        .build();
            }
            return INSTANCE;
        }
    private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
            @Override
            public void migrate(@NonNull SupportSQLiteDatabase database) {
    
                // 需要执行 SQL 语句
                database.execSQL("ALTER TABLE word ADD COLUMN sex INTEGER NOT NULL DEFAULT 1");
            }
        };
    

    如果要删除 column 就要先创建一个 新的 表, 把原来的数据复制,然后删除旧表,改名新表...

    相关文章

      网友评论

          本文标题:Jetpack_Room

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