Powerful Android ORM: greenDAO 3 Tutorial




Persisting data is an essential requirement of any application. In Android, we can persist data generally by three modes.

  1. SQLite
  2. SharedPreferences
  3. File System

The simplest way to persist data is by using the SQLite database and working through SqliteOpenHelper. This approach requires writing raw queries and manipulation through cursors. It becomes difficult to manage when code base becomes large and it is also prone to manual errors. The solution to this is using Data Access Objects or DAOs. In this article, we will explore the data persistence through DAOs using greenDAO.

greenDAO is an open source Android ORM making development for SQLite databases easy. It relieves developers from dealing with low-level database requirements while saving development time. greenDAO frees you from writing SQL and parsing query results, which are quite tedious and time-consuming tasks, by mapping Java objects to database tables (called ORM “object/relational mapping”). This way you can store, update, delete, and query for Java objects using a simple object-oriented API.

greenDAO 3 uses Annotation Processing to generate the DAO classes.

Let’s go through an active example to setup and get going with greenDAO 3. We will follow a stepwise process for the sake of this tutorial.


STEP 1:

Provide the Gradle dependency in app/build.gradle.

compile 'org.greenrobot:greendao:3.2.2'


STEP 2:

Provide the greenDAO Gradle plugin for the Annotation processing in the project’s build.gradle.

classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'

Then use this plugin in the app/build.gradle, below com.android.application plugin

apply plugin: 'org.greenrobot.greendao'


STEP 3:

GreenDAO requires us to create the schema of the table in the form of a class with greenDAO annotations. Let’s create a user table with few properties.

Create a class User.java


@Entity(nameInDb = "user")
public class User {

    @Id(autoincrement = true)
    private Long id;

    @Property(nameInDb = "name")
    private String name;

    @Property(nameInDb = "created_at")
    private String createdAt;

    @Property(nameInDb = "updated_at")
    private String updatedAt;
}

When you build the project, it will generate getter, setters, and constructors for this class.

  1. @Entity : It defines the table name in the database.
  2. @Id : It defines the primary key of the table.
  3. @Property : It defines the row name in the user table.

STEP 4:

Explore the DAO generated classes at app/build/generated/source/greendao. We can see few classes in this folder.

1. DaoMaster : This class defines the methods for database creation and manipulation.

2. DaoSession : This class provides the DAO classes for accessing the database tables.

3. UserDao : This class wraps the User table and defines the Queries for it.


STEP 5:

To use the database we need to construct the DaoSession Object.

Create A class DemoApp which extends android.app.Application and mention it in the AndroidManifest.xml


public class DemoApp extends Application {

    private DaoSession mDaoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        mDaoSession = new DaoMaster(
                new DaoMaster.DevOpenHelper(this, "greendao_demo.db").getWritableDb()).newSession();

        // USER CREATION FOR DEMO PURPOSE
        if(mDaoSession.getUserDao().loadAll().size() == 0){
            mDaoSession.getUserDao().insert(new User(1L, "Janishar Ali","", ""));
        }
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }
}

In AndroidManifest.xml add android:name=".DemoApp" :


application
    ...
    android:name=".DemoApp"
    ...



STEP 6:

Test user table in MainActivity.java


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.text);

        // Put this in a different thread or use AsyncSession in greenDAO.
        // For Demo purpose, this query is made on main thread but it should in a different thread.
        User user = ((DemoApp)getApplication()).getDaoSession().getUserDao().load(1L);

        if(user != null){
            textView.setText(user.getName());
        }
    }
}

You can see the user name appear in the main_activity textview.


STEP 7:

You should not use DevOpenHelper, as we have used in the DemoApp DaoSession creation. This is because with a new app version, you would want to modify the database schema or alter the table. For this purpose provide a custom OpenHelper to the DaoMaster.

Create a class DbOpenHelper


public class DbOpenHelper extends DaoMaster.OpenHelper {

    public DbOpenHelper(Context context, String name) {
        super(context, name);
    }

    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
        super.onUpgrade(db, oldVersion, newVersion);
        Log.d("DEBUG", "DB_OLD_VERSION : " + oldVersion + ", DB_NEW_VERSION : " + newVersion);
        switch (oldVersion) {
            case 1:
            case 2:
                //db.execSQL("ALTER TABLE " + UserDao.TABLENAME + " ADD COLUMN " + UserDao.Properties.Name.columnName + " TEXT DEFAULT 'DEFAULT_VAL'");
        }
    }
}

Modify the DemoApp onCreate method and use DbOpenHelper class:


    @Override
    public void onCreate() {
        super.onCreate();
        mDaoSession =
                new DaoMaster(new DbOpenHelper(this, "greendao_demo.db").getWritableDb()).newSession();

        // USER CREATION FOR DEMO PURPOSE
        if(mDaoSession.getUserDao().loadAll().size() == 0){
            mDaoSession.getUserDao().insert(new User(1L, "Janishar Ali","", ""));
        }
    }

Reinstall the App and now the custom OpenHelper(DbOpenHelper) will be used.


STEP 8:

You will need to specify the schema version of the database so that you can get the old version and new version when the app is upgraded. To specify this add greendao schema in the app/build.gradle .


android {
	...
}

greendao {
    schemaVersion 1
}

When you upgrade the schema in the new app version, increase this schema Version. You should handle the upgrade code in onUpgrade method of the DbOpenHelper class.

This completes the basic setup and usage of greenDAO. You can also work with joins and relations with greenDAO.

See this project android-mvp-architecture to find greenDAO3 complete use with RxJava


Check out all the Mindorks best articles here.


Thanks for reading this article. Be sure to share this article if you found it helpful. It would let others get this article and spread the knowledge.

Also, Let’s become friends on Twitter , Linkedin , Github , and Facebook .

Learning is a journey, let’s learn together!