A Simple DBFlow Tutorial

DBFlow is simple and powerful Android ORM database library with annotation processing.

Install and configure

Add classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8’ to dependencies of buildscript and maven { url “https://jitpack.io” } to reposities of allscripts in your root’s gradle.build. Here is how it looks after adding these lines:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
        //add the following line for DBFLow
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        //add the following line for DBFLow
        maven { url "https://jitpack.io" } 
    }
}

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

We will apply android-apt plugin and add DBFlow dependency in app’s gradle.build.

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

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"

    defaultConfig {
        applicationId "com.androidnames.dbflowexample"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

def dbflow_version = "3.1.1"

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'

    apt "com.github.Raizlabs.DBFlow:dbflow-processor:${dbflow_version}"
    // use kapt for kotlin apt
    compile "com.github.Raizlabs.DBFlow:dbflow-core:${dbflow_version}"
    compile "com.github.Raizlabs.DBFlow:dbflow:${dbflow_version}"
    // kotlin extensions
    compile "com.github.Raizlabs.DBFlow:dbflow-kotlinextensions:${dbflow_version}"

}

To initialize the database, add FlowManager.init(new FlowConfig.Builder(this).build()); to MainActivity’s onCreate method.

FlowManager.init(new FlowConfig.Builder(this).build());

Create a database

Annotation @Database is used to declare a database. It will contain both database’s name and version. Version is often set as 1 when starting a project. The number is increased when there are changes in schema. Create a class with the same name:

public class CompanyDatabase {

    public static final String NAME = "CompanyDatabase";

    public static final int VERSION = 1;
}

Create tables

The Java object needs to extend from BaseModel for DBFlow to recognize it as a model. Annotation @Table is used to define a class as model. Let’s create 2 models, Department and Employee.

@Table(database = CompanyDatabase.class)
public class Department extends BaseModel{
    @Column
    @PrimaryKey
    private int id;

    @Column
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@Table(database = CompanyDatabase.class)
public class Employee extends BaseModel {
    @Column
    @PrimaryKey
    private int id;

    @Column
    private String name;

    @Column
    private int age;

    @Column
    @ForeignKey(saveForeignKeyModel = false)
    private Department department;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
}

CRUD operations

Create and update objects
save() method is used to add a row to table. If a row already existed, it updates the database with the object’s new values.

Department department = new Department();
department.setName("Human Resources");
department.save();

Read objects
Class with suffix “_Table” is generated automatically. It contains convenience Properties which provide easy SQL operations.

List<Department> departments = new Select().from(Department.class).queryList();
List<Employee> employees = new Select()
        .from(Employee.class)
        .where(Employee_Table.department_id.is(1))
        .and((Employee_Table.age.greaterThan(20)))
        .queryList();

Delete objects
It is quite simple, just call delete() method.

employee.delete();