使用具有复合主键的 GreenDAO 3.X 创建实体
为具有复合主键的表创建模型时,对于模型实体,Object 需要进行额外的工作以遵守这些约束。
以下示例 SQL 表和实体演示了存储客户为在线商店中的项目留下的评论的结构。在此示例中,我们希望 customer_id
和 item_id
列是复合主键,只允许在特定客户和项目之间存在一个审核。
SQL 表
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)
);
通常我们会在实体类的相应字段上方使用 @Id
和 @Unique
注释,但是对于复合主键,我们执行以下操作:
-
在类级
@Entity
注释中添加@Index
注释。value 属性包含构成键的字段的逗号分隔列表。使用如图所示的unique
属性来强制密钥的唯一性。 -
GreenDAO 要求每个实体都有一个
long
或Long
对象作为主键。我们仍然需要将它添加到 Entity 类,但是我们不需要使用它或担心它会影响我们的实现。在下面的例子中,它被称为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;
@NotNull
private Integer star_rating;
private String content;
public Review() {}
}