我使用 Android Room 持久性库作为 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 来表示“无关系”会导致
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);
关于java - SQLiteConstraintException : How to map "no relationship" with a FOREIGN KEY in Room,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749812/