Jetpack_Room

可以快速流暢的訪問 Sqlite 數(shù)據(jù)庫
查看jetpack 官方文檔,導(dǎo)入依賴

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);
          
          ...

最基礎(chǔ)的使用如上
升級版 引入LiveData,AsyncTask 要糊,ViewModel , 在ViewModel 中再使用Repository將數(shù)據(jù)庫操作封裝。
WordRepository

package com.bg.ppjoke.db;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import java.util.List;

/**
 * 單獨操作數(shù)據(jù)庫
 */
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);
    }


    /**
     * 插入任務(wù) ;
     */
    static class InsertAsyncTask extends AsyncTask<Word, Void, Void> {

        @Override
        protected Void doInBackground(Word... words) {
            wordDao.insert(words);
            return null;
        }
    }


    /**
     * 全部刪除 任務(wù) ;
     */
    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 實現(xiàn)單例

@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
暴力行為 送粱,不保留原來數(shù)據(jù)旷坦, 或者直接卸載app

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

如果要保留原有數(shù)據(jù)

 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) {

            // 需要執(zhí)行 SQL 語句
            database.execSQL("ALTER TABLE word ADD COLUMN sex INTEGER NOT NULL DEFAULT 1");
        }
    };

如果要刪除 column 就要先創(chuàng)建一個 新的 表, 把原來的數(shù)據(jù)復(fù)制使鹅,然后刪除舊表绝淡,改名新表...

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末缠捌,一起剝皮案震驚了整個濱河市锄贷,隨后出現(xiàn)的幾起案子译蒂,更是在濱河造成了極大的恐慌,老刑警劉巖谊却,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件柔昼,死亡現(xiàn)場離奇詭異,居然都是意外死亡炎辨,警方通過查閱死者的電腦和手機捕透,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來碴萧,“玉大人乙嘀,你說我怎么就攤上這事∑朴鳎” “怎么了虎谢?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長曹质。 經(jīng)常有香客問我婴噩,道長,這世上最難降的妖魔是什么羽德? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任几莽,我火速辦了婚禮,結(jié)果婚禮上宅静,老公的妹妹穿的比我還像新娘章蚣。我一直安慰自己,他們只是感情好姨夹,可當(dāng)我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布究驴。 她就那樣靜靜地躺著,像睡著了一般匀伏。 火紅的嫁衣襯著肌膚如雪洒忧。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天够颠,我揣著相機與錄音熙侍,去河邊找鬼。 笑死履磨,一個胖子當(dāng)著我的面吹牛蛉抓,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播剃诅,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼巷送,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了矛辕?” 一聲冷哼從身側(cè)響起笑跛,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤付魔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后飞蹂,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體几苍,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年陈哑,在試婚紗的時候發(fā)現(xiàn)自己被綠了妻坝。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡惊窖,死狀恐怖刽宪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情界酒,我是刑警寧澤纠屋,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站盾计,受9級特大地震影響售担,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜署辉,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一族铆、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧哭尝,春花似錦哥攘、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至桶唐,卻和暖如春栅葡,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背尤泽。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工欣簇, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人坯约。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓熊咽,卻偏偏與公主長得像,于是被迫代替她去往敵國和親闹丐。 傳聞我的和親對象是個殘疾皇子横殴,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容