Android--Database GreenDao use

1. Introduction

greenDAO is an Object Relational Mapping (ORM) framework that provides an interface to operate relational databases by manipulating objects, which makes it easier and more convenient for you to operate databases. As shown below:


Github address: https://github.com/greenrobot/greenDAO

GreenDao advantages:

1. High performance, known as the fastest relational database in Android
2. Small memory footprint
3. The library file is relatively small, less than 100K, the compilation time is low, and the 65K method limit can be avoided
4. Support database encryption greendao supports SQLCipher for database encryption SQLCipher can refer to this blog Android data storage Sqlite uses SQLCipher database encryption practice
5. Simple and easy-to-use API

Two, placement

1. You need to add dependencies to the project's build.gradle

buildscript {
    repositories {
        jcenter ()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'
        //GreenDao3 dependency
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }
}

2. Add dependencies to the build.gradle of the project (Module)

apply plugin: 'com.android.application'
// use greendao
apply plugin: 'org.greenrobot.greendao'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.handsome.didi"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    //greendao configuration
    greendao {
        //version number, configurable when upgrading
        schema version 1                             
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}


dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    //greendao dependency
    compile 'org.greenrobot:greendao:3.2.0'
}

3. Use

1. Create a Bean object (table name and field name)

After GreenDao needs to create a bean object, the bean object is the table name, and its attribute value is the field name. The implementation is realized by annotation. The following is the bean object of the shopping cart (each bean object corresponds to a table )

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;

/**
 * app entity class
 */

@Entity
public class app {
    // can't use int
    @Id(autoincrement = true)
    private Long id;
    private String packageName;
    private String label;
    private String versionName;
    private int versionCode;
    private String sourceDir;
    private String dataDir;
    private boolean system;
    private boolean installed;
    @Generated(hash = 1362904721)
    public app(Long id, String packageName, String label, String versionName,
            int versionCode, String sourceDir, String dataDir, boolean system,
            boolean installed) {
        this.id = id;
        this.packageName = packageName;
        this.label = label;
        this.versionName = versionName;
        this.versionCode = versionCode;
        this.sourceDir = sourceDir;
        this.dataDir = dataDir;
        this.system = system;
        this.installed = installed;
    }
    @Generated(hash = 1515546537)
    public app() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getPackageName() {
        return this.packageName;
    }
    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }
    public String getLabel() {
        return this.label;
    }
    public void setLabel(String label) {
        this.label = label;
    }
    public String getVersionName() {
        return this.versionName;
    }
    public void setVersionName(String versionName) {
        this.versionName = versionName;
    }
    public int getVersionCode() {
        return this.versionCode;
    }
    public void setVersionCode(int versionCode) {
        this.versionCode = versionCode;
    }
    public String getSourceDir() {
        return this.sourceDir;
    }
    public void setSourceDir(String sourceDir) {
        this.sourceDir = sourceDir;
    }
    public String getDataDir() {
        return this.dataDir;
    }
    public void setDataDir(String dataDir) {
        this.dataDir = dataDir;
    }
    public boolean getSystem() {
        return this.system;
    }
    public void setSystem(boolean system) {
        this.system = system;
    }
    public boolean getInstalled() {
        return this.installed;
    }
    public void setInstalled(boolean installed) {
        this.installed = installed;
    }
    
}

It should be noted here that after the creation is completed, build gradle is required to complete the automatic generation of our code. The automatically generated code has

  1. Bean entity constructor and get and set methods
  2. DaoMaster、DaoSession、DAOS类

The annotation of the Bean object is explained here

  1. @Entity: Tell GreenDao that the object is an entity, and only the bean class annotated with @Entity can be operated by the dao class
  2. @Id: The Id of the object, use the Long type as the EntityId, otherwise an error will be reported. (autoincrement = true) means that the primary key will be incremented automatically, if false, the old value will be used
  3. @Property: You can customize the field name, note that foreign keys cannot use this property
  4. @NotNull: Property cannot be null
  5. @Transient: Properties using this annotation will not be stored in fields in the database
  6. @Unique: The attribute value must be unique in the database
  7. @Generated: Annotations for automatically generated constructors, methods, etc. after compilation, indicating that constructors, methods, etc. cannot be modified

2. GreenDao database creation

public class MyApplication extends Application {

    private static DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        //configure the database
        setupDatabase();
    }

    /**
     * Configuration database
     */
    private void setupDatabase() {
        //Create database app.db"
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "app.db", null);
        //get writable database
        SQLiteDatabase db = helper.getWritableDatabase();
        //get database object
        DaoMaster daoMaster = new DaoMaster(db);
        //Get the Dao object manager
        daoSession = daoMaster.newSession();
    }

    public static DaoSession getDaoInstant() {
        return daoSession;
    }
}

It can be found that GreenDao has shortened the creation of our database into a few sentences, and the code will automatically create the Bean object into a table, which is no longer a traditional handwritten SQL statement. The database creation here only needs to be executed once in the Application, here are several classes explained

  • DevOpenHelper: Concrete implementation of SQLiteOpenHelper for creating SQLite databases
  • DaoMaster: The top-level object of GreenDao, as a database object, used to create and delete tables
  • DaoSession: manages all Dao objects, and there are APIs such as addition, deletion, modification and query in Dao objects

Since we have created the Bean objects of DaoSession and Shop, our ShopDao object will be automatically generated after compilation, which can be obtained through DaoSession

AppDao dao = daoSession.getAppDao();

Dao (Data Access Object) here refers to the data access interface, that is, it provides some API interfaces for database operations, and can be added, deleted, modified, and searched through dao.

3. Add, delete, modify and check the database

public class utilsDao {

    /**
     * Add data, overwrite if there are duplicates
     *
     * @param shop
     */
    public static void insertLove(app shop) {
        BaseApplication.getDaoInstant().getShopDao().insertOrReplace(shop);
    }

    /**
     * delete data
     *
     * @param id
     */
    public static void deleteLove(long id) {
        BaseApplication.getDaoInstant().getShopDao().deleteByKey(id);
    }

    /**
     * update data
     *
     * @param shop
     */
    public static void updateLove(app shop) {
        BaseApplication.getDaoInstant().getShopDao().update(shop);
    }

    /**
     * The query condition is the data of Label=second shot
     *
     * @return
     */
    public static List<app> queryLove() {
        return BaseApplication.getAppDao().queryBuilder().where(appDao.Properties.Label.eq("秒拍")).list();
    }

    /**
     * Query all data
     */
    public static List<app> queryAll() {
        return BaseApplication.getDaoInstant().getShopDao().loadAll();
    }

}

The effect is obvious. The package of GreenDao is more compact and clear, and the semantics are clear. The following is an introduction to other APIs of Dao objects in GreenDao.

  • add single data 
    • getShopDao().insert(shop);
    • getShopDao().insertOrReplace(shop);
  • Add multiple data 
    • getShopDao().insertInTx(shopList);
    • getShopDao().insertOrReplaceInTx(shopList);
  • Inquire all 
    • List< Shop> list = getShopDao().loadAll();
    • List< Shop> list = getShopDao().queryBuilder().list();
  • query with a single condition attached 
    • .where()
    • .whereOr()
  • query with multiple conditions attached 
    • .where(, , ,)
    • .whereOr(, , ,)
  • Query additional sort 
    • .orderDesc()
    • .orderAsc()
  • Query limit the number of current pages 
    • .limit()
  • The total number of queries 
    • .count()
  • Modify a single data 
    • getShopDao().update(shop);
  • Modify multiple data 
    • getShopDao().updateInTx(shopList);
  • delete single data 
    • getTABUserDao().delete(user);
  • delete multiple data 
    • getUserDao().deleteInTx(userList);
  • delete dataByKey 
    • getTABUserDao().deleteByKey();


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325859538&siteId=291194637