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

你。 提交于 2019-12-24 01:13:06

问题


I am using the Android Room Persistence Library as ORM.

I have the following Entity:

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

    // ...
}

There are some log entries which have a serving and some which don't. Adding a log entry which has a serving works fine, but adding one with id = 0 to represent 'no relation' causes a SQLiteConstraintException with the message

FOREIGN KEY constraint failed

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

db.logEntryDao().add(logEntry);

So, how can I express the fact that a log entry has no serving in Room?


回答1:


You need to use Long as datatype and insert the entity with null as servingId.

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

db.logEntryDao().add(logEntry);


来源:https://stackoverflow.com/questions/44749812/sqliteconstraintexception-how-to-map-no-relationship-with-a-foreign-key-in-ro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!