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
CREATE TABLE review (
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:
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
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() {}
}