Sessions

The (generated) DaoSession class is one of the central interface to greenDAO. As a start, DaoSession provides developers access to basic entity operations and DAOs for a more complete set of operations. Sessions also mange an identity scope for entities.

DaoMaster and DaoSession

As documented in the Getting Started section, you will need to create a DaoMaster to get a DaoSession:

daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
noteDao = daoSession.getNoteDao();

Notice that the database connection belongs to the DaoMaster, so multiple sessions refer to the same database connection. New sessions can be created quite quickly. However, each session allocates memory, typically an session “cache” for entities.

Identity scope and session “cache”

If you have two queries returning the same database object, how many Java objects to work with; one or two? It depends on the identity scope. The default in greenDAO (the behavior is configurable) is that multiple queries return the same Java objects. For example, loading an User object in the USER table with ID 42 will result in the same Java object for each query.

A side effect of this is some kind of “caching” entities. If an entity is still around in memory (greenDAO uses weak references here), the entity will not be constructed again with values from the database. For example, if you load an entity by its ID and you have loaded the entity before, greenDAO does not need query the database. Instead, it will return the object “immediately” from the session cache, which is one or two magnitudes faster.

Concepts

This documentation page will be extended in the future. For now please refer to Hibernate’s session to grasp the concept of sessions and identity scopes.