GreenDAO is an Object-Relational Mapping library to help developers use SQLite databases for persistent local storage.
Creating an Entity with GreenDAO 3.X that has a Composite Primary Key
When creating a model for a table that has a composite primary key, additional work is required on the Object for the model Entity to respect those constraints.
The following example SQL table and Entity demonstrates the structure to store a review left by a customer for an item in an online store. In this example, we want the customer_id and item_id columns to be a composite primary key, allowing only one review to exist between a specific customer and item.
Usually we would use the @Id and @Unique annotations above the respective fields in the entity class, however for a composite primary key we do the following:
Add the @Index annotation inside the class-level @Entity annotation. The value property contains a comma-delimited list of the fields that make up the key. Use the unique property as shown to enforce uniqueness on the key.
GreenDAO requires every Entity have a long or Long object as a primary key. We still need to add this to the Entity class, however we do not need to use it or worry about it affecting our implementation. In the example below it is called localID
Getting started with GreenDao v3.X
After adding the GreenDao library dependency and Gradle plugin, we need to first create an entity object.
An entity is a Plain Old Java Object (POJO) that models some data in the database. GreenDao will use this class to create a table in the SQLite database and automatically generate helper classes we can use to access and store data without having to write SQL statements.
One-time GreenDao setup
Each time an application is launched GreenDao needs to be initialized. GreenDao suggests keeping this code in an Application class or somewhere it will only be run once.
GreenDao Helper Classes
After the entity object is created, GreenDao automatically creates the helper classes used to interact with the database. These are named similarly to the name of the entity object that was created, followed by Dao and are retrieved from the daoSession object.
Many typical database actions can now be performed using this Dao object with the entity object.
Helper methods for SELECT, INSERT, DELETE, UPDATE queries
This example shows a helper class that contains methods useful, when executing the queries for data. Every method here uses Java Generic's in order to be very flexible.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0