体验Android ORM之DBFlow



DBFlow综合了 Active Android, Schematic, Ollie,Sprinkles 等库的优点;不通过消耗性能的反射而通过注解实现,性能优秀(Referer

https://github.com/Raizlabs/DBFlow

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文件,搞了一整下午都是泪呀,一点提示都没有。。。。