Android Jetpack - Room的使用

1.先做資料庫Entity(Table) 的class

2.再做資料庫的Dao,利用第一步做的Entity(Table)進行增刪查改等...SQL行為

3.最後建立Database物件管理眾多的 Dao 物件

Entity(Table)

@Entity代表此類別為一個table,一個資料表一定要有一個Primary key,用@PrimaryKey表示。

@NonNull表示該欄位值不可為空值

若加上@ColumnInofo表示為該欄位取名

@Entity
public class Expense {
    //要設計主key
    @PrimaryKey(autoGenerate = true) //自動產生
    int id;

    @NonNull
    @ColumnInfo(name = "onCreate")
    String date;

    @NonNull
    String info;

    @NonNull
    int amount;

    public Expense(@NonNull String date, @NonNull String info, int amount) {
        this.date = date;
        this.info = info;
        this.amount = amount;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    
    ..............
    
}

Dao

負責處理所有對資料庫資料進行增刪查改的行為

@Insert表示新增資料

@Query表示查詢資料

@Delete表示刪除資料

@Update表示更新資料

DataBase

建立資料庫物件,提供一個外界操作DB的instance,宣告用到哪些Entity(Table)。Room.datavaseBuilder(Context, DataBase, DB名稱).build()可以建立一個資料庫。

在此用工廠方法提供唯一一個資料庫操作物件給外部操作。

提供一個abstract方法讓外部取得某個table。

如何操作資料庫

資料庫的輸入輸出都屬於耗時工作,所以要建立一個新的Thread去執行。

以後new Thread不要用了,改用ExecutorService。有執行緒池讓執行緒可以重複利用

Last updated

Was this helpful?