Creating an Entity with GreenDAO 3.X that has a Composite Primary Key
suggest changeWhen 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:
- Add the
@Indexannotation inside the class-level@Entityannotation. The value property contains a comma-delimited list of the fields that make up the key. Use theuniqueproperty as shown to enforce uniqueness on the key. - GreenDAO requires every entity to have a
longorLongprimary key. Add that field to the entity. The example calls itlocalID. 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() {}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents