Android GreenDAO ORM的使用(一) 生成DAO和Bean

1. 什麼是GreenDAO?

greenDAO is an open source Android ORM making development for SQLite databases fun again. It relieves developers from dealing with low-level database requirements while saving development time. SQLite is an awesome embedded relational database. Still, writing SQL and parsing query results are quite tedious and time-consuming tasks. greenDAO frees you from these by mapping Java objects to database tables (called ORM, “object/relational mapping”). This way you can store, update, delete, and query for Java objects using a simple object oriented API.

這是greenDAO的自我介紹,大概意思就是greenDAO是針對於Android平臺的SQLite的ORM(Object/Relational Mapping)對象關係映射框架。他可以將Java對象映射到數據庫表,並幫你封裝了增刪改查的操作。
GreenDAO

2. 配置GreenDAO

2.1 Your Project

// 在build.gradle(Project:YourProjectName)添加
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
    }
}
// 在build.gradle(Module:app)添加
apply plugin: 'org.greenrobot.greendao'

greendao {
    targetGenDir 'src/main/java'
}
dependencies {
    compile 'org.greenrobot:greendao:3.1.0'
}

2.2 Generator Lib

首先新建一個Module,File->New->New Module…->Java Libarary,命名爲GreenDaoGenLib
greendaogenlib
創建完成後在項目左側會出現一個如下圖所示的Lib包,且下方Gradle Script中會出現一個對應的gradle配置的地方
創建完成

// 在build.gradle(Module:greendaogenlib)中添加
dependencies {
    compile 'org.greenrobot:greendao-generator:3.1.0'
}
// 創建一個類Config用於輸出配置
public class Config {
    static final int VERSION = 1;
    static final String DEFAULT_PACKAGE = "org.greendaotest.db.greendao";  // 輸出包名
    static final String OUTDIR = "/Users/rita/Documents/Projects/GreenDAOTest/app/src/main/java";  // 輸出文件位置
}

之後打開Generator開始編輯

package org.greendao;

import org.greenrobot.greendao.generator.DaoGenerator;
import org.greenrobot.greendao.generator.Entity;
import org.greenrobot.greendao.generator.Property;
import org.greenrobot.greendao.generator.Schema;
import org.greenrobot.greendao.generator.ToMany;

/**
 * com.tixmate.tixmate.dataaccess.database.greenDAO
 * Created by ritaliu.
 */

public class Generator {
    private static Schema schema;

    public static void main(String[] args) throws Exception {

        //創建模式對象,指定版本號和自動生成的bean對象的包名
        schema = new Schema(Config.VERSION, Config.DEFAULT_PACKAGE);

        //添加所有實體
        addEntity();

        //調用DaoGenerator().generateAll方法自動生成代碼到創建的目錄下
        new DaoGenerator().generateAll(schema, Config.OUTDIR);

    }

    private static void addEntity()
    {
        //添加一個實體,自動生成實體Entity類
        Entity account = schema.addEntity("Account");
        Entity moment = schema.addEntity("Moment");

        /* Account */     
               account.addStringProperty("id").primaryKey().getProperty();  //添加ID, 主鍵
        account.addStringProperty("name").notNull();  //添加String類型的name,不能爲空
        account.addStringProperty("avatarlink");  //添加String類型的Link


        /* Moment */ 
        moment.addStringProperty("id").primaryKey().getProperty();
        moment.addIntProperty("type").notNull();
        moment.addStringProperty("text");
        moment.addDateProperty("time").notNull();
    }

}

上面的代碼中簡單的生成了兩張表Account和Moment,其中個包含一些字段,字段類型可直接使用addXXProperty來定義。一般的ID都是使用Long型的就夠了,所以GreenDAO提供了一個addIdProperty()的方法,默認爲Long型且會被設置爲主鍵,如不能滿足你的需求可以自行添加一個字段,並把他設置爲primaryKey。另外GreenDao還提供了字段自增、字段不爲空等設置,具體可以參看官網的document。

2. 使用GreenDAO生成實體類和DAOs

上面的Generator編輯完成後,運行這個java類,會看到在之前約定輸出的OUTDIR的位置出現了兩個包,分別爲org.greendaotest.db.bean和org.greendaotest.db.dao,會看到如下的目錄結構。
greendao生成
在bean目錄中生成了兩個實體類,Account和Moment,在dao目錄中生成了兩個對應的Dao和一個DaoMaster一個DaoSession。
那麼DaoMaster和DaoSession是做什麼的呢?官方是這樣說的
Core-Classes

DaoMaster: The entry point for using greenDAO. DaoMaster holds the database object (SQLiteDatabase) and manages DAO classes (not objects) for a specific schema. It has static methods to create the tables or drop them. Its inner classes OpenHelper and DevOpenHelper are SQLiteOpenHelper implementations that create the schema in the SQLite database.

DaoSession: Manages all available DAO objects for a specific schema, which you can acquire using one of the getter methods. DaoSession provides also some generic persistence methods like insert, load, update, refresh and delete for entities. Lastly, a DaoSession objects also keeps track of an identity scope. For more details, have a look at the session documentation.

DAOs: Data access objects (DAOs) persists and queries for entities. For each entity, greenDAO generates a DAO. It has more persistence methods than the DaoSession, for example: count, loadAll, and insertInTx.

Entities: Persistable objects. Usually, entities are generated (you do not have to), and are objects representing a database row using standard Java properties (like a POJO or a JavaBean).

2.1 DAOMaster

DAOMaster的作用是使用greenDAO的入口。DaoMaster持有了Database的對象並且管理DAO的類(不是對象)。它包括了建表和刪除表的靜態方法。它的內部類OpenHelper和DevOpenHelper是SQLiteOpenHelper的實現,實現了在SQLite數據庫中創建schema。

2.2 DAOSession

DAOSession管理所有可用的使用特定Schema的DAO對象,你可以從中獲得它們的Getter方法。DAOSession提供了一些一般的持久化方法,像一些簡單的增刪改查操作。並且,DaoSession可以持續追蹤一個ID,貌似是用來緩存部分查詢結果進行提速的,詳情查看Session Documention

2.3 DAOs

DAOs是數據訪問對象,是從數據庫存儲和查詢實體的通道。對於每一個實體,greenDAO都會創建一個DAO。他相對於DaoSession有更多的持久化方法,例如,count,loadAll,insertInTx。

2.4 Entities

Entities是持久化對象。通常,實體根據數據庫的字段創建。

2.5 使用

下面是基本的使用方法

DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(mContext, "DB_NAME", null);
DaoMaster daoMaster = new DaoMaster(helper.getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
Account accountDao = daoSession.getAccountDao();

本文只是介紹了使用GreenDAO提供的Generator生成DAO和Bean的方法,簡單的生成了兩張表,但是既然SQLite是關係型數據庫,那麼表間怎麼能沒有關係存在呢?下篇我將介紹如何添加關係,包括1:1, 1:n和n:m三種關係。

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