SQLiteConstraintException:如何在 Room 中使用 FOREIGN KEY 映射 "no relationship"

SQLiteConstraintException: How to map "no relationship" with a FOREIGN KEY in Room

我正在使用 Android Room Persistence Library 作为 ORM。

我有以下实体:

@Entity(tableName = "log_entries",
        foreignKeys = {
                @ForeignKey(
                        entity = Serving.class,
                        parentColumns = "id",
                        childColumns = "foodId",
                        onDelete = ForeignKey.CASCADE
                )
        }
)
public class LogEntry {

    @PrimaryKey(autoGenerate = true)
    private long id;

    private long servingId;

    // ...
}

有些日志条目有服务,有些则没有。添加日志条目 它有一个服务工作正常,但是添加一个 id = 0 来表示 'no relation' 会导致 SQLiteConstraintException 消息

FOREIGN KEY constraint failed

// ...
LogEntry logEntry = new LogEntry();
logEntry.setServingId(0);
// ...

db.logEntryDao().add(logEntry);

那么,我如何表达一个日志条目在 Room 中没有服务呢?

您需要使用 Long 作为数据类型并插入带有 null 的实体作为 servingId

// ...
LogEntry logEntry = new LogEntry();
logEntry.setServingId(null);
// ...

db.logEntryDao().add(logEntry);