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, the entity class needs extra annotations so those constraints are respected.

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

CREATE TABLE review (
    customer_id TEXT NOT NULL,
    item_id TEXT NOT NULL,
    star_rating INTEGER NOT NULL,
    content TEXT,
    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 to have a long or Long primary key. Add that field to the entity. The example calls it localID. The unique index above is what enforces one review per customer and item.

Entity

@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;

    @NotNull
    private Integer star_rating;

    private String content;

    public Review() {}
}

Feedback about page:

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



Table Of Contents