Android ORM framework greenDao uses

Keywords: Java Database Android SQLite

Preface:

In the development process, data storage operations are always carried out. When files do not meet the requirements, they are stored using SQLite. As a result, many ORM frameworks have emerged. Here I choose to use greenDao as the database framework of the project. GreenDao is the most efficient of all open source frameworks for Android database ORM, as described on the official website: probably the fastest ORM for Android.

But the green Dao learning curve is not as simple as other frameworks, and it has its own strengths and weaknesses. This article is my own notes and summary of the process of using green Dao. Mainly read a lot of official documents, its official documents than a few months ago written much better, and very clear, easy to understand.

Green Daode features:

  • Maximum performance (probably the fastest ORM for Android)
    performance optimization
  • Easy to use but powerful APIs covering relations and joins
    Easy to use, API convenient
  • Minimal memory consumption
    Minimizing memory footprint
  • Small library size to keep your build times low and to avoid the 65k method limit
    Green Dao Library

Usage method:

1. Adding dependencies

  1. In the Android app project
    Adding dependencies: compile'de.green robot: greendao: 2.1.0'
  2. Create Java Libray
    Adding dependencies: compile'de.green robot: greendao-generator: 2.1.0'

2. Create a java-gen directory

Create a java-gen directory in the src/main directory of Android app to store the files generated by greenDao.
And add sourceSets in build.gradle.

android {
    ...

    //Add sourceSets to add the created java-gen.
    sourceSets {
        main {
            java.srcDirs = ['src/main/java', 'src/main/java-gen']
        }
    }
}

3. Write Java entity classes and generate code

public class MyClass {
  public static void main(String[] args) throws Exception {

    //Create Schema schema objects
    //Two parameters, the database version number and the package path for automatically generating code
    Schema schema = new Schema(1, "baiiu.greendao.gen");

    //Add entity
    addEntity(schema);

    //Generate code. Use relative paths
    new DaoGenerator().generateAll(schema,"../ZhihuDaily/app/src/main/java-gen");
  }

    //Adding Entity Classes
  private static void addEntity(Schema schema) {
    //Create entity classes, Person indicates the creation of Person tables
    Entity topStory = schema.addEntity("Person");

    topStory.addIdProperty();
    topStory.addStringProperty("name");
    topStory.addStringProperty("age");

  }
}

After the data storage object is written, the main() method run s to generate the response class under the specified path.

For more definitions of Entity, see the official website, which is really very detailed. modelling-entities.

4. Introduction to Green Dao Generating Core Classes

DaoMaster:

The entry point for using greenDAO. DaoMaster holds the database object (SQLiteDatabase) and manages * DAO classes (not objects) for a specific schema.*

Use the green Dao entrance. This class holds the SQLiteDatabase object and manages the generated entity class object. class.


DaoSession:

Manages all available DAO objects for a specific schema, which you can acquire using one of the getter methods.

DaoSession manages all Dao objects generated by schema and provides getter() methods to get the Dao object.


DAOs (Data Access objects):

DAOs persists and queries for entities. For each entity, greenDAO generates a DAO. It has more persistence methods than the DaoSession.

Daos provides persistent, accessible methods for these entity classes. For each Entitiy, greenDao generates a corresponding DAO, which provides more methods than DaoSession.


Entities:

Persistable objects. Usually, entities are generated.
Persistent objects. Usually generated by green Dao.



5. Initialize and start using:

Official website introduction:

    DaoMaster.DevOpenHelper helper =
        new DaoMaster.DevOpenHelper(UIUtil.getContext(), DB_NAME, null);
    SQLiteDatabase db = helper.getWritableDatabase();

    //Get the DaoMaster object
    DaoMaster daoMaster = new DaoMaster(db);

    //Get the DaoSession object, which holds various EntitiyDao s
    DaoSession daoSession = daoMaster.newSession();

    //Entity class Dao, used to manipulate databases
    EntityDao entityDao = daoSession.getEntityDao();

In project practice, we usually have a DBManger for storage. Through this layer, we can encapsulate another layer of database to replace the database conveniently later.

The code is as follows, using the singleton pattern to get DaoSession, and then using daoSession to get other XxxDao.

public class DBManager {
  private static final String DB_NAME = "daily-db";

  private static DBManager dbManager;//Singleton object

  //daoSession member variable, through which other Daos can be obtained
  private DaoSession daoSession;

  private DBManager() {
    //Initialize greenDao
    DaoMaster.DevOpenHelper helper =
        new DaoMaster.DevOpenHelper(UIUtil.getContext(), DB_NAME, null);
    SQLiteDatabase db = helper.getWritableDatabase();
    DaoMaster daoMaster = new DaoMaster(db);
    daoSession = daoMaster.newSession();//Get daoSession
  }

  //Single case
  public static DBManager instance() {
    if (dbManager == null) {
      synchronized (DBManager.class) {
        if (dbManager == null) {
          dbManager = new DBManager();
        }
      }
    }

    return dbManager;
  }

  //Get dao
  private SavedStoryDao getSavedStoryDao() {
    return daoSession.getSavedStoryDao();
  }

  //Storage list
  public void saveStoryList(List<SavedStory> list) {
    getSavedStoryDao().insertOrReplaceInTx(list);
  }

  //Read list
  public List<SavedStory> getStoryList(String date) {
    List<SavedStory> savedStories =
       getSavedStoryDao().queryBuilder().where(SavedStoryDao.Properties.Date.eq(date)).list();
    return savedStories;
  }
}

This may not be the best way. Many other things on the Internet are to put the initialization process in the application and then get it through the application object.

Conclusion:

Green Dao used it before, and this time it's been sorted out. I believe that as more and more people use it, they will use it better and better.

Relevant uses in github On the project.


Reference resources:
green-dao official website
greenDao documentation
tangqi's MyGreen DAO <- The notes are clear and quick to use.
Summary of GreenDao's Learning Experience and Use of ORM Framework in Database

Posted by kumaran on Sun, 07 Apr 2019 14:24:31 -0700