Getting started with DBFlow for Android high-performance ORM databases, ormdbflow
DBFlow integrates the advantages of libraries such as ActiveAndroid, Schematic, Ollie, and Sprinkles. At the same time, it is not based on reflection, so the performance is also very high, and the efficiency is closely followed by greenDAO. Based on annotations, apt technology is used to generate operation classes during compilation, which is highly similar to ActiveAndroid and easy to use.
Features: 1. seamless support for multiple databases; 2. Use annotation processing to increase the speed; 3. The ModelContainer class library can directly parse data such as JSON; 4. Added flexible interfaces. Github warehouse: https://github.com/Raizlabs/DBFlow
There may not be many people using DBFlow in China, so there are very few Chinese introductions, so this article is available. Let's learn about DBFlow together.
1. Introduce dependencies and initialize
Apt and maven need to be introduced to build. gradle for configuration items
buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.0.0-beta6' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' }}allprojects { repositories { jcenter() maven { url "https://jitpack.io" } }}
Configure app 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 "cn.taoweiji.dbflowexample" minSdkVersion 14 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }}dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) 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}"}
DBFlow needs to be initialized in onCreate of Application
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); FlowManager.init(this); }}
Remember to modify AndroidManifest. xml
<application android:name=".MyApplication"../>
Ii. database creation and table Creation
Define Database
I have defined a database named AppDatabase, which can be defined as I like.
@ Database (name = AppDatabase. NAME, version = AppDatabase. VERSION) public class AppDatabase {// database NAME public static final String NAME = "AppDatabase"; // database VERSION number public static final int VERSION = 1 ;}
Create database objects
BaseModel must be inherited. BaseModel contains basic database operations (save, delete, update, insert, and exists). The following Code shows that the table is associated with the database defined above, the id of People is an auto-increment id.
@ ModelContainer @ Table (database = AppDatabase. class) public class People extends BaseModel {// auto-increment ID @ PrimaryKey (autoincrement = true) public Long id; @ Column public String name; @ Column public int gender ;}
After writing the data table object, click build-> Make Project of Android studio (command + F9 for Mac kids shoes) to compile the data table using apt,
View the directory (my people class is placed in cn. taoweiji. dbflowexample. db)
App/build/generated/source/apt/debug/cn/taoweiji/dbflowexample/db
You can see that lele_adapter, People_Container, and People_Table are automatically generated. People_Table plays a major role in subsequent use. We recommend that you look at its structure in detail.
3. add, delete, and modify
Because the data table object inherits the BaseModel, it already contains many operations.
People people = new People();people.name = "Wiki";people.gender = 1;people.save();//people.update();//people.delete();Log.e("Test", String.valueOf(people.id));
Delete, update, and other operations on your own, this is not to be said here.
Iv. Query
// Returns the List of all query results <People> distinct les = new Select (). from (People. class ). queryList (); // returns the results of a single query: People people = new Select (). from (People. class ). querySingle (); // query all PeopleList <People> peoples2 = new Select () for gender = 1 (). from (People. class ). where (lele_table.gender.eq (1 )). queryList ();
DBFlow's query method draws on ActiveAndroid, but it is more powerful than ActiveAndroid.
Iv. Transaction and batch Storage
A transaction is a must-have of data. If 10000 pieces of data are saved, one row must be saved slowly. Therefore, you need to use transactions to store them in batches. DBFlow transactions are very powerful and complicated to use at the same time. Here is a brief introduction to batch saving. For more information, see the official documentation.
Https://github.com/Raizlabs/DBFlow/blob/master/usage/Transactions.md
List <People> distinct les = new ArrayList <> (); for (int I = 0; I <1000; I ++) {People people = new People (); people. name = "Wiki"; people. gender = 1; Les. add (people);} // save in real time. Save new SaveModelTransaction immediately <> (ProcessModelInfo. withModels (Les )). onExecute (); // save asynchronously and use Asynchronization. If you query immediately, the result may not be found. // TransactionManager. getInstance (). addTransaction (new SaveModelTransaction <> (ProcessModelInfo. withModels (Les )));
5. Database Upgrade (adding tables, adding fields, etc)
If you want to add a table without special processing, you can directly modify the AppDatabase version.
To add a new field, in addition to modifying the AppDatabase version number, special processing is required. The description of DBFlow is Migrations.
Example: add an email field to People
Step 2: Modify the database version
@ Database (name = AppDatabase. NAME, version = AppDatabase. VERSION) public class AppDatabase {// database NAME public static final String NAME = "AppDatabase"; // database VERSION number. Here, modify 2 public static final int VERSION = 2 ;}
Step 2: Modify the data table object structure and add an email
@ ModelContainer @ Table (database = AppDatabase. class) public class People extends BaseModel {// auto-increment ID @ PrimaryKey (autoincrement = true) public Long id; @ Column public String name; @ Column public int gender; @ Column public String email ;}
Step 2: After step 2 is executed, you need to build (Android studio build-> Make Project, Mac kids shoes directly command + F9), update People_Table through apt, and then write Migrations
@Migration(version = 2, database = AppDatabase.class)public class Migration_2_People extends AlterTableMigration<People> { public Migration_2_People(Class<People> table) { super(table); } @Override public void onPreMigrate() { addColumn(SQLiteType.TEXT, People_Table.email.getNameAlias().getName()); }}
The class name can be better defined by myself. My personal rule is to name the class according to the database version number and the data table to be updated. Note that: version = 2
The Database Upgrade is complete.
Summary: This article briefly introduces the basic functions of DBFlow. DBFlow also has many amazing functions, such as multi-database support and Powerful Model Caching, it also supports the Kotlin language (the new language running on the Java Virtual Machine ). I have only used greenDAO, activeAndroid, afinal, and DBFlow databases, so in my opinion, DBFlow is the best database I have used. It has good performance and is very simple to use, highly recommended.
I will share the configuration of DBFlow on github.
Https://github.com/taoweiji/DBFlowExample