1. 程式人生 > >體驗Android ORM之DBFlow

體驗Android ORM之DBFlow

DBFlow綜合了 Active Android, Schematic, Ollie,Sprinkles 等庫的優點;不通過消耗效能的反射而通過註解實現,效能好(Referer);

1.為什麼使用DBFlow?
如果要執行下面這一條SQL語句:

SELECT * FROM Ant where type = 'worker' AND isMale = 0;

如果安安穩穩的使用Android提供的SqliteHelper的話:

String[] args = new String[2];
args[0] = "worker";
args[1] = "0";
Cursor cursor = db.rawQuery
("SELECT * FROM Ant where type = ? AND isMale = ?", args); final List<Ant> ants = new ArrayList<Ant>(); Ant ant; if (cursor.moveToFirst()) { do { // get each column and then set it on each ant = new Ant(); ant.setId(cursor.getLong(cursor.getColumnIndex("id"))); ant.setType
(cursor.getString(cursor.getColumnIndex("type"))); ant.setIsMale(cursor.getInt(cursor.getColumnIndex("isMale") == 1); ant.setQueenId(cursor.getLong(cursor.getColumnIndex("queen_id"))); ants.add(ant); } while (cursor.moveToNext()); }

但使用DBFlow:

// main thread retrieval
List<Ant> devices = SQLite.select
().from(Ant.class) .where(Ant_Table.type.eq("worker")) .and(Ant_Table.isMale.eq(false)).queryList(); // Async Transaction Queue Retrieval (Recommended for large queries) SQLite.select() .from(DeviceObject.class) .where(Ant_Table.type.eq("worker")) .and(Ant_Table.isMale.eq(false)) .async().queryList(transactionListener);

簡潔,清晰,明瞭。看起來就很爽,而且想出錯都難。
類似於插入,更新,刪除都是類似這樣簡潔。

2.整合
在專案的跟build.gradle中:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0-alpha5'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

allProjects {
  repositories {
    jcenter()
    // required to find the project's artifacts
    maven { url "https://jitpack.io" }
  }
}

在app或者Module的build.gradle中修改:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

def dbflow_version = "3.0.0-beta4"

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.znn.androiddemo"
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
    apt "com.github.Raizlabs.DBFlow:dbflow-processor:${dbflow_version}"
    compile "com.github.Raizlabs.DBFlow:dbflow-core:${dbflow_version}"
    compile "com.github.Raizlabs.DBFlow:dbflow:${dbflow_version}"
    // sql-cipher database encyrption (optional)
    compile "com.github.Raizlabs.DBFlow:dbflow-sqlcipher:${dbflow_version}"

}

(DBFlow是使用apt在編譯前動態生成配置的資料庫和表的相關Java檔案,所以新增完表配置後需要build->Make Project,就會自動在app->build->generated->source->apt->debug->package….->config/db…下生成相應的檔案)

配置資料庫:

@Database(name = AppDatabase.NAME, version = AppDatabase.VERSION)
public class AppDatabase {
  //資料庫名稱
  public static final String NAME = "AppDatabase";
  //資料庫版本號
  public static final int VERSION = 1;
}

配置表結構:

@Table(database = AppDatabase.class)
public class News extends BaseModel{
    @PrimaryKey(autoincrement = true)
    long id;
    @Column
    String title;
    @Column
    String url;
}

欄位必須是包內可訪問,或者public或者private(有get/set).
至少有一個主鍵。繼承BaseModel,BaseModel本身已實現save(),insert(),delete()等操作方法。

另外需要在Application的onCreate()方法進行初始化:

FlowManager.init(this);

TIPS:
如果配置好了後,Make Project後,卻沒有生成_Table, GeneratedDatabaseHolder, _DataBase, _Adapter等,檢查都無誤後,可以檢查一下:

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    }

這個引數,之前用 compileSdkVersion 22 的 死活不生成Java檔案,搞了一整下午都是淚呀,一點提示都沒有。。。。

原文