如何在房间数据库中添加主键?

How to add primary key in room database?

我有一个 sqlite 数据库,我想将我的数据库更改为 Room database

其中一个 table 没有任何主键,只有两个外键。

我使用此查询在房间之前创建了 table:

CREATE TABLE student_performance(
class_id int , 
student_id char(10), 
class_date date , 
absent boolean DEFAULT 0, 
delay boolean DEFAULT 0, 
positive int DEFAULT 0, 
negative int DEFAULT 0, 
quiz float ,
FOREIGN KEY (student_id , class_id) REFERENCES student(student_id , class_id) 
ON DELETE CASCADE 
ON UPDATE CASCADE);

现在我为房间定义 table:

@Entity(tableName = "performance",
    foreignKeys = {@ForeignKey(
            entity = StudentEntry.class,
            parentColumns = {CLASS_ID, STUDENT_ID},
            childColumns = {CLASS_ID, STUDENT_ID},
            onDelete = CASCADE, onUpdate = CASCADE)})
public class PerformanceEntry {
    .
    .
    .
}

但它给出了错误:

error: An entity must have at least 1 field annotated with @PrimaryKey

我不知道如何为房间数据库定义这个 table。

示例:

primaryKeys = {"class_id", "lastName", "class_date", ... , "quiz"})

在关系数据库中,当您没有任何主键时,意味着所有字段都是主键。

当您使用 ORM 时,您通常应该为您的实体定义一个 Id 属性。

当存在 tableName@ColumnInfo 注释时,不必 运行 CREATE TABLE SQL。添加主键 entry_id(因为 class_id 几乎是唯一的):

@Entity(
    tableName = "performance",
    foreignKeys = {
        @ForeignKey(
            entity = StudentEntry.class,
            parentColumns = {CLASS_ID, STUDENT_ID},
            childColumns = {CLASS_ID, STUDENT_ID},
            onDelete = CASCADE,
            onUpdate = CASCADE
       )
   }
)
public class PerformanceEntry  {

    /* Fields */
    @ColumnInfo(name = "entry_id")
    @PrimaryKey(autoGenerate = true)
    private int entryId;

    ...
}

检查the official doc

只需使用 @PrimaryKey 注释即可。

Each entity must define at least 1 field as a primary key. Even when there is only 1 field, you still need to annotate the field with the @PrimaryKey annotation. Also, if you want Room to assign automatic IDs to entities, you can set the @PrimaryKey's autoGenerate property. If the entity has a composite primary key, you can use the primaryKeys property of the @Entity annotation, as shown in the following code snippet:

类似于:

@Entity(...)
public class PerformanceEntry {
    @PrimaryKey
    public int class_id;

    //..

}

@Entity(...)
public class PerformanceEntry {
    @PrimaryKey(autoGenerate = true)

    //..

}

您需要使用自动生成属性

你的注释应该是这样的:

@PrimaryKey(autoGenerate = true)