首页 > 解决方案 > 如何在房间数据库中添加主键?

问题描述

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

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

我用这个查询在房间前创建了表:

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

现在我为房间定义表:

@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

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

标签: androidandroid-sqliteandroid-roomandroid-database

解决方案


当存在注释时,不必运行CREATE TABLESQL 。添加一个主键(因为几乎是唯一的):tableName@ColumnInfoentry_idclass_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;

    ...
}

推荐阅读