The original article was first published on wechat public number: Jzman-blog, welcome to follow and exchange!

DBFlow is an easy to use ORM Android database based on annotation processor development, the library simplifies a lot of redundant code, and provides a good API to handle the interaction with the database, let developers focus on App development. The following will learn the use of DBFlow database framework from the following aspects, as follows:

  1. The advantage of DBFlow
  2. Configuration DBFlow
  3. Creating a database
  4. Create a table
  5. Insert data
  6. Delete the data
  7. Update the data
  8. Query data
  9. case

The advantage of DBFlow

DBFlow borrows some of the features of other excellent database frameworks. Here are the advantages of DBFlow:

  1. Extensibility: There is no limit to which table classes can be inherited. It can be a plain JavaBean. You can extend non-model classes in different packages and use them as database tables for ease of reference. And they can be in different packages.
  2. Speed: The library is based on Java annotation processor generation, using it has almost no impact on runtime performance (reflection is only used for generation of raw database modules), saves time on boilerplate code generation, supports model caching (multi-primary key model), and is faster than native SQLite when possible. Lazy loading, @foreignKey, @onetomany and so on are supported to make the query more efficient.
  3. SQLite Query Flow: DBFlow queries are as close to native SQLite queries as possible, for example:
select(name, screenSize).from(Android.class).where(name.is("Nexus 5x")). And (version) is (6.0)). QuerySingle ()Copy the code
  1. Open Source: Github for DBFlow
  2. Robust (Robust) : support Trigger, ModelView, Index, Migration and built-in database management methods, in addition, also support SQLCipher, RXJava, etc
  3. Multiple Databases, Multiple Modules: Seamless support for Multiple database files and other dependent database models using DBFlow
  4. Built On SQLite: SQLite is the most widely used database engine in the world, and it is not limited to one platform.

Configuration DBFlow

Since DBFlow is still not officially released, you need to configure DBFlow in your project’s build.gradle file as follows:

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io"}}}Copy the code

Then add dependencies to the build.gradle file for your Module as follows:

// Use the def keyword to define the version number for convenience
def dbFlow_version = "4.2.4"
dependencies {
    / /...
    annotationProcessor "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}"
}
Copy the code

The dependencies in the above code are only for Java, if you want to use Kotlin, RxJava, etc., you need to configure the corresponding dependencies.

Note: When upgrading a new version of DBFlow, it is important to remove the dependency of the old version, because the old version may have different annotation handlers. If the old version is not removed, the following error will be reported:

java.lang.NoSuchMethodError: com.raizlabs.android.dbflow.annotation.Table.tableName()Ljava/lang/String
Copy the code

Then, customize the Application and initialize DBFlow in the corresponding onCreate() method as follows:

/** * Custom Application *@author jzman
 * create at 2018/4/16 0016 17:28
 */
public class MyApplication extends Application{
    @Override
    public void onCreate(a) {
        super.onCreate();
        // Initialize DBFlow
        FlowManager.init(new FlowConfig.Builder(this).build());
        // Set the log displayFlowLog.setMinimumLoggingLevel(FlowLog.Level.V); }}Copy the code

Finally, use the custom Application in the Androidmanifest.xml file as follows:

<application
    android:name=".app.MyApplication"
    // ...
</application>
Copy the code

At this point, DBFlow is introduced into the current project.

Creating a database

Create a class and use the @Database annotation to define your own Database. This class should define the name and version of the Database as follows:

/**
 * MyDatabase
 * @author jzman
 * create at 2018/4/17 0017 9:08
 */
@Database(name = MyDatabase.NAME, version = MyDatabase.VERSION)
public class MyDatabase {
    // Database name
    public static final String NAME = "MyDatabase";
    // Database version number
    public static final int VERSION = 1;
}
Copy the code

Note: If you want to change the structure of any table, you must change the version number to avoid conflicts with the old version database, and ensure that the version number is only up.

Create a table

The model class of the table generally needs to inherit from BaseModel and add the @column annotation to each field of the model class. This annotation maps the fields of the model class to the columns of the corresponding table and defines a table as follows:

/**
 * NoteTable.java
 * @author jzman
 * create at 2018/4/17 0017 9:54
 */
@Table(database = MyDatabase.class)
public class NoteTable extends BaseModel {
    @Column
    @PrimaryKey
    int id;
    @Column
    private String title;
    @Column
    private String date;
    @Column
    private String content;

    public String getTitle(a) {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDate(a) {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getContent(a) {
        return content;
    }

    public void setContent(String content) {
        this.content = content; }}Copy the code

Note: At least one field in a table must be defined as the primary key. If a field in a model class is private, you must define the corresponding getter and setter methods. Otherwise, you will fail to create the table.

java.lang.IllegalArgumentException: expected type but was null
Copy the code

Insert data

There are two common ways to insert data using DBFlow, as follows:

  1. model.insert()
  2. SQLite.insert()

The former is used for the insertion of a single model class object. After creating a specific object, call model.insert() to insert the corresponding record of the object. The latter uses SQLite Wrapper Language to insert data, which is similar to the native INSERT statement and supports multiple column data inserts.

/** * Insert data *@param model
 */
public void inseartData(NoteBean model){
    //1.model,insert()
    model.setTitle("title");
    model.setDate("2018-04-17");
    model.setContent("content");
    model.insert();
    //2.SQLite.insert()
    SQLite.insert(NoteBean.class)
            .columns(NoteBean_Table.title,NoteBean_Table.date,NoteBean_Table.content)
            .values("title"."2018-04-17"."content")
            .execute();
}
Copy the code

Delete the data

There are two common ways to delete data using DBFlow, as follows:

  1. Model.delete () : Deletes a record
  2. Sqlite.delete () : Delete according to the condition

The former is used to delete a single model class object. After creating a specific object, call model.delete() to delete the corresponding record of the object. The latter uses SQLite Wrapper Language to conditionally delete data, which is similar to the native DELETE statement and is more convenient to use. See the following for details:

/** * delete data *@param model
 */
public void deleteData(NoteBean model){
    //1.model.delete()
    model.delete();
    //2.SQLite.delete()
    SQLite.delete(NoteBean.class)
            .where(NoteBean_Table.title.is("title"))
            .and(NoteBean_Table.id.is(10))
            .async()
            .execute();
    // Delete the entire table
    Delete.table(NoteBean.class);
    // Delete multiple tables
    Delete.table(NoteBean.class,NoteBean1.class);
}
Copy the code

Update the data

There are two common ways to delete data using DBFlow, as follows:

  1. Model.update () : Updates a record
  2. Sqlite.update () : updates a record based on a condition

The former is used for updating a single model class object. After creating a specific object, call model.update() to update the corresponding record of the object. The latter uses SQLite Wrapper Language to conditionally delete data, which is similar to the native UPDATE statement.

/** * Update data *@param model
 */
public void updateData(NoteBean model) {
    //1.model.update()
    model.update();
    //2.SQLite.update()
    SQLite.update(NoteBean.class)
            .set(NoteBean_Table.title.eq("title"),
                    NoteBean_Table.content.eq("content"))
            .where(NoteBean_Table.id.is(10))
            .async()
            .execute();
}
Copy the code

Query data

Select () from sqlite.select (); select() from sqlite.select ()

/** * query data */
public List<NoteBean> queryData(a){
    // Query by condition
    List<NoteBean> noteBeans = SQLite.select()
            .from(NoteBean.class)
            .where(NoteBean_Table.title.is("title"))
            .queryList();
    return noteBeans;
}
Copy the code

Note: You can use the model.save() method for insert and update operations.

case

DBFlow configuration and add, delete, change, check and other basic operations, DBFlow has other more advanced uses, such as using Transactions for data security operations, etc., the following is a simple case to end the study of DBFlow, specific effects are as follows:

For more information about DBFlow, see the DBFlow GitBook.

If you think it will help you, you can follow the wechat official account jzman-blog to communicate and learn together.