1. 程式人生 > >關於GreenDao3.0的使用

關於GreenDao3.0的使用

首先我們要考慮,為什麼要使用GreenDao


根據這個圖,我們可以簡單的判斷下自己到底需要什麼,如果想知道更多的細節,請查詢: http://greenrobot.org/android/android-orm-performance-2016/ 
說完為什麼使用,我們就可以開始學習如何使用GreenDao


一、安裝並配置環境

首先,我搭配的是Android Studio(AS)環境使用的GreenDao3.2.2,GreenDao的安裝很簡單,在AS裡配置兩個檔案, AS就可以開始使用
GreenDao了,並不需要下載GreenDao。
關於配置兩個檔案,分別是專案下的兩個build.gradle 在專案主目錄下的build.gradle,如下
buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

在app目錄下的build.gradle,新增,其中加粗位置需要注意
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.android.test001"
        minSdkVersion 9
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    greendao {
        schemaVersion 1 //資料庫版本號
        daoPackage 'com.usher.greendao_demo.greendao.gen' //自動生成的工具類的包名
        targetGenDir 'src/main/java' //路徑
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'org.greenrobot:greendao:3.2.2'
}

新增完之後AS會提醒同步,同步完成之後,就可以使用GreenDao了

二、開始使用

首先我們要建立一個Entity類,也就是實體類,每一個實體類就相當於資料庫中的一個表,而類中的每個屬性就相當於表的一個列;而在GreenDao3.0以上,我們可以使用註解的方式告訴AS這是一個特殊的類,是針對GreenDao建表使用的
@Entity
public class Patient {
    @Id(autoincrement = true)
    private Long idPatient;
    private String firstName;
    private String middleName;
    private String lastName;
}

有幾個屬性非常重要: @Entity 提示這是針對GreenDao @Id 提示下一行必須是Long,並且是主鍵    (autoincrement = true)主鍵自增長
建立好類後,點選Android studio上的Build----make project,系統就會自動生成三個檔案DaoMaster, DaoSession和關於你自建類的PatientDao 然後就可以進行一些基本操作
由於GreenDao是相對於一個類進行建表的,所以對錶進行新增記錄,刪除記錄,更新記錄,查詢記錄,這些操作在程式碼上看都是相對於類進行的操作 比如插入一條記錄
    public void insertUser(Patient patient) {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        PatientDao patientDao = daoSession.getPatientDao();
        patientDao.insert(patient);
    }
其餘的比如刪除記錄,更新記錄都類似,都是使用PatientDao進行操作

三、進階使用


在我們正常的使用中,一般都是多表在一起進行搭配使用,這就要考慮到一一對應,一對多,多對多

比如一一對應,一個人只有一個頭,一對多,一個學生有好幾個科目成績,一群老師和一群學生是多對多的
最簡單的一一對應,
 @ToOne(joinProperty = ”屬性名“)

這就是簡單的一一對應,在使用joinProperty時,後面的屬性名最好是long或者int型
@Entity
public class People{
    @Id(autoincrement = true)
    private Long id;
    private String name;
    private long idHead;
    @ToOne(joinProperty = "idHead")
    private Head head;
}
@Entity
public class Head {
    @Id(autoincrement = true)
    private Long id;
}
也就是說,在People中定義了一個外來鍵,並通過@ToOne告訴GreenDao關於這個外來鍵我要指向的類,一樣進行重新make project,系統會自動生成程式碼
一對多(簡單分為學生Student和成績Score),使用 @ToMany分為兩種情況,
1.Score的主鍵在Student中,並當做外來鍵使用
    @ToMany(referencedJoinProperty = “scoreId”)

2.Student中並不存在Score的主鍵,我想自己在Score中定義一個外來鍵scoreSn,然後在Studeng中定義一個對應的studentSn,這樣外來鍵可以使用String型
    @ToMany(joinProperties = {
            @JoinProperty(name = "scoreSn", referencedName = "studentSn")
    })