Use of Android database framework dbflow

Dbflow is a convenient ORM Android database developed based on the annotation processor. The library simplifies a lot of redundant code and provides a useful API to handle the interaction with the database, allowing developers to focus on app development. Next, we will learn the use of dbflow database framework from the following aspects: 1. Advantages of dbflow 2. Configure dbflow 3. Create database 4. Create table 5. Insert data 6. Delete data 7. Update data 8. Query data 9. Cases

Dbflow draws on the characteristics of some other excellent database frameworks. The following are the advantages of dbflow, which are as follows: 1. Extensibility: there are no restrictions on the inheritance class of table class, which can be an ordinary JavaBean. In order to facilitate the recommendation that table class inherit basemodel class, you can extend non model classes in different packages and use them as database tables. In addition, You can add subclasses of other tables to @ column, and they can be located in different packages. 2. Speed: the library is generated based on the Java annotation processor. Using it has little impact on the runtime performance (reflection is only used to generate the database module). It can save the time for generating the template code, support the model cache (multi primary key model), and is faster than the native SQLite if possible. It supports lazy loading, @ ForeignKey @Onetomany and others make queries more efficient. 3. SQLite query flow: the query of dbflow should be as close to the original SQLite query as possible, such as:

select(name,screenSize).from(Android.class).where(name.is("Nexus 5x")).and(version.is(6.0)).querySingle()

Because dbflow is still not officially released, you need to configure it in the build.gradle file of the project as follows:

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

Then, add dependencies in the build.gradle file corresponding to the module, as follows:

//为了方便可使用 def 关键字定义版本号
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}"
}

The dependencies in the above code are only for Java. If you want to use kotlin, rxjava, etc., you can configure the corresponding dependencies.

Note: when upgrading a new version of dbflow, be sure to delete the dependency of the old version, because the annotation processors of the old and new versions may be different. If the old version is not removed, the following error will be reported, as follows:

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

Then, customize the application and initialize dbflow in the corresponding oncreate() method, as follows:

/**
 * 自定义Application
 * @author jzman
 * create at 2018/4/16 0016 17:28
 */
public class MyApplication extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        //初始化DBFlow
        FlowManager.init(new FlowConfig.Builder(this).build());
        //设置日志显示
        FlowLog.setMinimumLoggingLevel(FlowLog.Level.V);
    }
}

Finally, use the custom application in the androidmanifest.xml file, as follows:

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

At this point, dbflow will be introduced into the current project.

Create a class and use the @ database annotation to define its 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 {
    //数据库名称
    public static final String NAME = "MyDatabase";
    //数据库版本号
    public static final int VERSION = 1;
}

Note: if you want to modify the structure of any table in the future, in order to avoid conflict with the old version database, you must modify the version number and ensure that the version number only increases but not decreases.

The table can be created after the database has been created. The model class of the table generally needs to inherit the basemodel, and add @ column annotation for each field in the model class. This annotation will map the field of the model class to the column in the corresponding table, and define 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() {
        return title;
    }

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

    public String getDate() {
        return date;
    }

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

    public String getContent() {
        return content;
    }

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

Note: at least one field in a table must be defined as the primary key. If a field in the model class is private, the corresponding getter and setter methods must be defined, otherwise it will fail in the process of creating the table. The hump naming method shall be used for table naming, otherwise the following problems may occur:

java.lang.IllegalArgumentException: expected type but was null

There are two common ways to insert data using dbflow, as follows: 1. Model. Insert() 2. SQLite. Insert()

The former is used for inserting a single model class object. After creating the concrete object, calling model.insert () can insert the corresponding record of the object. The latter uses SQLite wrapper language to insert data, which is similar to the original insert statement. It supports the insertion of multi column data and is convenient to use. For details, see the following:

/**
 * 插入数据
 * @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();
}

There are two common ways to delete data using dbflow, as follows: 1. Model. Delete(): delete a record; 2. SQLite. Delete(): delete according to conditions

The former is used for deleting a single model class object. After creating the specific object, calling model.delete () can 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. For details, see the following:

/**
 * 删除数据
 * @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.table(NoteBean.class);
    //删除多张表
    Delete.table(NoteBean.class,NoteBean1.class);
}

There are two common ways to delete data using dbflow, as follows: 1. Model. Update(): update a record; 2. SQLite. Update(): update a record according to conditions

The former is used for updating a single model class object. After the concrete object is created, model.update () can be used to update the records corresponding to the object. The latter uses SQLite wrapper language to conditionally delete data, which is similar to the native UPDATE statement. It is convenient to use. For details, see the following:

/**
 * 更新数据
 * @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();
}

SQLite. Select () method is used for query. There are many keywords that can be used as conditions for query, which will not be repeated here. The following is a common query made by a developer. For details, please refer to the following:

/**
 * 查询数据
 */
public List<NoteBean> queryData(){
    //根据条件查询
    List<NoteBean> noteBeans = sqlite.select()
            .from(NoteBean.class)
            .where(NoteBean_Table.title.is("title"))
            .queryList();
    return noteBeans;
}

Note: for insert and update operations, you can use the model. Save () method.

The above describes the basic operations such as dbflow configuration, addition, deletion, modification and query. Dbflow also has other advanced uses, such as using transactions for data security operations. Here is a simple case to end the learning of dbflow. The specific effects are as follows:

For more information about dbflow, please refer to dbflow's gitbook.

If you feel you are helpful, you can focus on WeChat official account: jzman-blog, and exchange learning.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>