Sessions

Contents

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

DaoMaster and DaoSession

As documented in the How to get started section, you will need to create a DaoMasterto get a DaoSession:

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

Identity scope and session “cache”

If you have two queries returning the same database object, how many Java objects are you working with: one or two? It depends entirely on the identity scope.

The default in greenDAO (the behavior is configurable) is that multiple queries return references to the same Java objects. For example, loading a User object from the USER table with ID 42 returns the same Java object for both queries.

A side effect of this is some kind of entity “caching”. If an entity object is still around in memory (greenDAO uses weak references here), the entity is not constructed again. Also, greenDAO performs no database query to update the entity values. Instead, the object is returned “immediately” from the session cache, which is one or two magnitudes faster.

Clear the identity scope

To clear the identity scope of the whole session so no “cached” objects are returned:

To clear the identity scope for just a single DAO:

Concepts

This documentation page currently has limited information. Please refer to Hibernate’s session to grasp the full concept of sessions and identity scopes.

Spread the love