Android ORM 框架之 greenDAO

GreenDao是一個用於Android開發的對象/關係映射(ORM)工具。它向SQLite數據庫提供了一個對象導向的接口。像GreenDao這樣的ORM工具不僅爲你省去了很多的重複工作,而且提供了更簡便的操作接口。

greenDAO 代碼生成的工程結構圖




GREENDAO 設計的主要目標

  • 一個精簡的庫

  • 性能最大化

  • 內存開銷最小化

  • 易於使用的 APIs

  • 對 Android 進行高度優化

GREENDAO 設計的主要特點

  • greenDAO 性能遠遠高於同類的 ORMLite

  • greenDAO 支持 protocol buffer(protobuf) 協議數據的直接存儲,如果你通過 protobuf 協議與服務器交互,將不需要任何的映射。

  • 與 ORMLite 等使用註解方式的 ORM 框架不同,greenDAO 使用「Code generation」的方式,這也是其性能能大幅提升的原因。

DAO CODE GENERATION PROJECT

這是其核心概念:爲了在我們的 Android 工程中使用 greenDAO ,我們需要另建一個純 Java Project,用於自動生成後繼 Android 工程中需要使用到的 Bean、DAO、DaoMaster、DaoSession 等類。

爲了在你的Android項目中使用GreenDao,你需要創建一個二級工程:“generator project”,它的任務就是爲你的domain生成具體的代碼。這個生成器工程就是一個普通的java工程。確保greenDao 的greenDao-generator.jar和 freemarker.jar 在classpath中。創建一個可執行的java類,構建你的實體模型並觸發代碼生成器,更多細節,可以參看 modelling文檔。

核心類

一旦生成了指定的代碼,就可以在你的android工程中使用greenDao了。別忘記在你的android工程中引入greenDao的核心jar包:greenDao.jar。以下是GreenDao的一些必要接口。


DaoMaster:

daomaster以一定的模式持有數據庫對象(SQLiteDatabase)並管理一些DAO類(而不是對象)。

有一個靜態的方法創建和drop數據庫表。它的內部類OpenHelper和DevOpenHelper是SQLiteOpenHelper的實現類,用於創建SQLite數據庫的模式。


DaoSession:

管理指定模式下所有可用的DAO對象,你可以通過某個get方法獲取到。DaoSession提供一些通用的持久化方法,比如對實體進行插入,加載,更新,刷新和刪除。最後DaoSession對象會跟蹤identity scope,更多細節,可以參看 session文檔。


DAOs(Data access objects):

數據訪問對象,用於實體的持久化和查詢。對於每一個實體,greenDao會生成一個DAO,相對於DaoSession它擁有更多持久化的方法,比如:加載全部,插入(insertInTx,語境不明瞭,暫且簡單的翻譯成插入)。


具體操作步驟:

Step1:在 ANDROID 工程中配置「GREENDAO GENERATOR」模塊

1.在 .src/main 目錄下新建一個與 java 同層級的「java-gen」目錄,用於存放由 greenDAO 生成的 Bean、DAO、DaoMaster、DaoSession 等類。

   new->Directory  (mingjava-gen)


2.配置 Android 工程(app)的 build.gradle,在android{}結構體中分別添加 sourceSets 與dependencies。 



 sourceSets {
        main {
            java.srcDirs = ['src/main/java', 'src/main/java-gen']
        }
    }

 compile 'org.greenrobot:greendao:2.2.0'

Step2:新建「GREENDAO GENERATOR」模塊 (純 JAVA 工程)
1.通過 File -> New -> New Module -> Java Library -> 填寫相應的包名與類名 -> Finish.


通過這種方式生成的Module結構(我起名爲greendao_generator )與一般情況不同

2.配置greendao_generator 工程的 build.gradle,添加 dependencies.
compile 'org.greenrobot:greendao-generator:2.2.0'

3.編寫 MyClass類,注意: 我們的 Java 工程只有一個類,它的內容決定了「GreenDao Generator」的輸出,你可以在這個類中通過對象、關係等創建數據庫結構,下面我將以註釋的形式詳細講解代碼內容。
package com.example;

import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;

public class MyClass{

    public static void main(String[] args) throws Exception {
        // 正如你所見的,你創建了一個用於添加實體(Entity)的模式(Schema)對象。
        // 兩個參數分別代表:數據庫版本號與自動生成代碼的包路徑。
        Schema schema = new Schema(1, "com.xionghu.greendao");
//      當然,如果你願意,你也可以分別指定生成的 Bean 與 DAO 類所在的目錄,只要如下所示:
//      Schema schema = new Schema(1, "me.itangqi.bean");
//      schema.setDefaultJavaPackageDao("me.itangqi.dao");

        // 模式(Schema)同時也擁有兩個默認的 flags,分別用來標示 entity 是否是 activie 以及是否使用 keep sections。
        // schema2.enableActiveEntitiesByDefault();
        // schema2.enableKeepSectionsByDefault();

        // 一旦你擁有了一個 Schema 對象後,你便可以使用它添加實體(Entities)了。
        addNote(schema);

        // 最後我們將使用 DAOGenerator 類的 generateAll() 方法自動生成代碼,此處你需要根據自己的情況更改輸出目錄(既之前創建的 java-gen)。
        // 其實,輸出目錄的路徑可以在 build.gradle 中設置,有興趣的朋友可以自行搜索,這裏就不再詳解。
        new DaoGenerator().generateAll(schema, "D:\\android_studio_4_6\\MyGreenDAO\\app\\src\\main\\java-gen");
    }

    /**
     * @param schema
     */
    private static void addNote(Schema schema) {
        // 一個實體(類)就關聯到數據庫中的一張表,此處表名爲「Note」(既類名)
        Entity note = schema.addEntity("Note");
        // 你也可以重新給表命名
        // note.setTableName("NODE");

        // greenDAO 會自動根據實體類的屬性值來創建表字段,並賦予默認值
        // 接下來你便可以設置表中的字段:
        note.addIdProperty();
        note.addStringProperty("text").notNull();
        // 與在 Java 中使用駝峯命名法不同,默認數據庫中的命名是使用大寫和下劃線來分割單詞的。
        // For example, a property called “creationDate” will become a database column “CREATION_DATE”.
        note.addStringProperty("comment");
        note.addDateProperty("date");
    }

}

Step3:

生成 DAO 文件(數據庫)

執行 generator 工程,如一切正常,你將會在控制檯看到如下日誌,並且在主工程「java-gen」下會發現生成了DaoMaster、DaoSession、NoteDao、Note共4個類文件。
在這裏需要對運行條件進行配置Android Studio 運行java程序






如圖 再點run ,生成以下程序




運行時的輸出框的正確信息


Step4:在 ANDROID 工程中進行數據庫操作
package com.cloudhome.mygreendao;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.xionghu.greendao.Note;
import com.xionghu.greendao.NoteDao;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;



public class MainActivity extends ListActivity {
    private EditText editText;
    private Cursor cursor;
    public static final String TAG = "DaoExample";
    private String orderBy;
    private String textColumn;
    private   SimpleCursorAdapter adapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textColumn = NoteDao.Properties.Text.columnName;

        orderBy=textColumn+" COLLATE LOCALIZED ASC";

        cursor = getDb().query(getNoteDao().getTablename(), getNoteDao().getAllColumns(), null, null, null, null, orderBy);


        String[] from = {textColumn, NoteDao.Properties.Comment.columnName};

        int[] to = {android.R.id.text1, android.R.id.text2};


        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from,
                to);

        setListAdapter(adapter);

        adapter.notifyDataSetChanged();


        editText = (EditText) findViewById(R.id.editTextNote);
    }

    private NoteDao getNoteDao() {
        // 通過 BaseApplication 類提供的 getDaoSession() 獲取具體 Dao
        return ((BaseApplication) this.getApplicationContext()).getDaoSession().getNoteDao();
    }

    private SQLiteDatabase getDb() {
        // 通過 BaseApplication 類提供的 getDb() 獲取具體 db
        return ((BaseApplication) this.getApplicationContext()).getDb();
    }

    /**
     * Button 點擊的監聽事件
     *
     * @param view
     */
    public void onMyButtonClick(View view) {
        switch (view.getId()) {
            case R.id.buttonAdd:
                addNote();
                break;
            case R.id.buttonQuery:
                search();
                break;
            default:
                ToastUtils.show(getApplicationContext(), "What's wrong ?");
                break;
        }
    }

    private void addNote() {
        String noteText = editText.getText().toString();
        editText.setText("");

        final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        String comment = "Added on " + df.format(new Date());

        if (noteText == null || noteText.equals("")) {
            ToastUtils.show(getApplicationContext(), "Please enter a note to add");
        } else {
            // 插入操作,簡單到只要你創建一個 Java 對象
            Note note = new Note(null, noteText, comment, new Date());
            getNoteDao().insert(note);
            Log.d(TAG, "Inserted new note, ID: " + note.getId());



            cursor = getDb().query(getNoteDao().getTablename(), getNoteDao().getAllColumns(), null, null, null, null, orderBy);

            String[] from = {textColumn, NoteDao.Properties.Comment.columnName};

            int[] to = {android.R.id.text1, android.R.id.text2};


            adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from,
                    to);

            setListAdapter(adapter);

            adapter.notifyDataSetChanged();


        }

    }

    private void search() {
        String noteText = editText.getText().toString();
        editText.setText("");
        if (noteText == null || noteText.equals("")) {
            ToastUtils.show(getApplicationContext(), "Please enter a note to query");
        } else {
            // Query 類代表了一個可以被重複執行的查詢
            Query query = getNoteDao().queryBuilder()
                    .where(NoteDao.Properties.Text.eq(noteText))
                    .orderAsc(NoteDao.Properties.Date)
                    .build();
            // 查詢結果以 List 返回
            List notes = query.list();
            ToastUtils.show(getApplicationContext(), "There have " + notes.size() + " records");
        }
        // 在 QueryBuilder 類中內置兩個 Flag 用於方便輸出執行的 SQL 語句與傳遞參數的值
        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;
    }

    /**
     * ListView 的監聽事件,用於刪除一個 Item
     *
     * @param l
     * @param v
     * @param position
     * @param id
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        // 刪除操作,你可以通過「id」也可以一次性刪除所有

        getNoteDao().deleteByKey(id);

//       getNoteDao().deleteAll();

        ToastUtils.show(getApplicationContext(), "Deleted note, ID: " + id);

        Log.d(TAG, "Deleted note, ID: " + id);

        cursor = getDb().query(getNoteDao().getTablename(), getNoteDao().getAllColumns(), null, null, null, null, orderBy);

        String[] from = {textColumn, NoteDao.Properties.Comment.columnName};

        int[] to = {android.R.id.text1, android.R.id.text2};


        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from,
                to);

        setListAdapter(adapter);

        adapter.notifyDataSetChanged();


    }


}

Step5:運行結果






參考資料:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章