Androrm - Android的ORM框架 - Androrm

openkk 12年前發布 | 49K 次閱讀 Android Android開發 移動開發

Androrm 是 Android 平臺上的一個對象關系映射框架,也就是我們常說的 ORM 框架。用于幫助你快速開發使用數據庫的應用,封裝了常用的表創建、對象讀寫和查詢,通過將 Model 類映射到數據庫表,直接對對象進行操作便可讀寫數據庫。

下面我們給出一個簡單的使用 Androrm 的教程:

1. 創建 Model 類

public class Book extends Model {

    // fields visibility is set to protected,
    // so the Model class can access it
    protected CharField mTitle;

    // zero-argument constructor, that can be called
    // by androrm, to gather field information
    public Book() {
        super();

        // set up field with maxLength parameter
        mTitle = new CharField(80);
    }

    public getTitle() {
        return mTitle.get();
    }

}
public class Author extends Model {

    protected CharField mName;

    public Author() {
        super();

        mName = new CharField(80);
    }

    public void getName() {
         return mName.get();
    }

    public void setName(String name) {
         mName.set(name);
    }

}

2. 創建數據庫

接下來我們需要在應用的 onCreate 方法中創建數據庫

List<Class<? extends Model>> models = new ArrayList<Class<? extends Model>>();
models.add(Author.class);
models.add(Book.class);                                                     

DatabaseAdapter.setDatabaseName("a_database_name");
DatabaseAdapter adapter = new DatabaseAdapter(getApplicationContext());
adapter.setModels(models);

3. 創建表關系

Androrm 有一個特殊的數據域——ForeignKeyField,通過它來定義外鍵關聯

public class Book extends Model {

    // fields visibility is set to protected,
    // so the Model class can access it
    protected CharField mTitle;

    // Link the Author model to the Book model.
    protected ForeignKeyField<Author> mAuthor;

    // zero-argument constructor, that can be called
    // by androrm, to gather field information
    public Book() {
        super();

        // set up field with maxLength parameter
        mTitle = new CharField(80);

        // initialize the foreign key relation
        mAuthor = new ForeignKeyField<Author>(Author.class);
    }

    public String getTitle() {
        return mTitle.get();
    }

   public void setAuthor(Author author) {
        mAuthor.set(author);
   }

}

4. 插入數據

// In your activity

Author author = new Author();
author.setName("My Author");
author.save(this);

Book book = new Book();
book.setName("Book name");
book.setAuthor(author);
book.save(this);

到此,整個簡單的教程到此結束,更詳細的關于 Androrm 的使用方法請參考文檔

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!