Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ActiveAndroid 使用手冊:Android SQLite ORM 入門

編輯:關於 Android 程式設計

ActiveAndroid 是一個 Android 上的 ORM 框架,可把 Java 物件與 SQLite 資料表做映射,減少手動拼接 SQL 的工作。

安裝

可下載 jar 放入 libs,或使用 Maven、Gradle 管理依賴。

compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'

也可從原始碼安裝:

git clone https://github.com/pardom/ActiveAndroid.git
cd ActiveAndroid
mvn clean install

初始化

在 AndroidManifest.xml 中設定資料庫名稱與版本,並讓 Application 繼承 ActiveAndroid 的 Application,或在自訂 Application 中呼叫初始化。

ActiveAndroid.initialize(this);

定義模型

@Table(name = "Items")
public class Item extends Model {
    @Column(name = "Name")
    public String name;
}

模型類別必須繼承 Model,欄位則以 Column 標註。ActiveAndroid 會自動建立主鍵。

保存資料

Item item = new Item();
item.name = "Example";
item.save();

查詢資料

List<Item> items = new Select()
    .from(Item.class)
    .orderBy("Name ASC")
    .execute();

資料庫遷移

若資料表需要變更,可在 assets/migrations 放入版本編號的 SQL 檔案,例如 2.sql,並提高 AA_DB_VERSION。

預設資料庫

若應用程式需要預先填入資料,可把 SQLite 檔案放在 assets,並設定 AA_DB_NAME。首次執行時,ActiveAndroid 會將其複製到應用程式的資料庫目錄。

ActiveAndroid 的優點是語法直觀、物件導向,適合中小型專案快速完成本機資料持久化;若需要更複雜的查詢或效能微調,仍需理解 SQLite 本身。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved