SQLiteConstraintException: How to map “no relation

2019-07-12 19:25发布

问题:

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