Introduction


greenDAO is an object/relational mapping (ORM) tool for Android. It offers an object oriented interface to the relational database SQLite. ORM tools like greenDAO do many repetitive tasks for you and offer a simple interface to your data.

DAO Code Generation Project


In order to use greenDAO in your Android project (usually an Eclipse project), you need to create a second project, the “generator project”. Its task is to generate code specific to your project domain. The generator project is an normal Java (not Android!) project. Make sure the greenDAO generator library (greenDAO-generator.jar) and the Freemarker library (freemarker.jar) are in its classpath. Create an executable Java class, model your entities and trigger the code generation. For details, have a look at the modelling documentation.

Core Classes

Once you generated your project specific code, you can start using greenDAO in your Android project. Don’t forget to include the greenDAO core library (greenDAO.jar) in your Android project.

The following core classes are the essential interface to greenDAO:

DaoMaster: The entry point for using greenDAO. DaoMaster holds the database object (SQLiteDatabase) and manages DAO classes (not objects) for a specific schema. It has static methods to create the tables or drop them. Its inner classes OpenHelper and DevOpenHelper are SQLiteOpenHelper implementations that create the schema in the SQLite database.

DaoSession: Manages all available DAO objects for a specific schema, which you can acquire using one of the getter methods. DaoSession provides also some generic persistence methods like insert, load, update, refresh and delete for entities. Lastly, a DaoSession objects also keeps track of an identity scope. For more details, have a look at the session documentation.

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, for example: count, loadAll, and insertInTx.

Entities: Persistable objects. Usually, entities are generated (you do not have to), and are objects representing a database row using standard Java properties (like a POJO or a JavaBean).

Core Initialization

The following code example illustrates the first steps to initialize the database and the core greenDAO classes:

helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
noteDao = daoSession.getNoteDao();

The example assumes having a “Note” entity. With its DAO (noteDao object), we can call the persistence operation for this specific entity.

Leave a Reply