Creating an Entity with GreenDAO 3.X that has a Composite Primary Key

suggest change

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.

SQL Table

    customer_id STRING NOT NULL,
    item_id STRING NOT NULL,
    star_rating INTEGER NOT NULL,
    content STRING,
    PRIMARY KEY (customer_id, item_id)

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:

  1. 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.
  2. 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


@Entity(indexes = { @Index(value = "customer_id,item_id", unique = true)})
public class Review {

    @Id(autoincrement = true)
    private Long localID;

    private String customer_id;
    private String item_id;

    private Integer star_rating;

    private String content;

    public Review() {}

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents