SQLiteConstraintException:如何映射“无关系”在房间里有一个外键 [英] SQLiteConstraintException: How to map "no relationship" with a FOREIGN KEY in Room

查看:195
本文介绍了SQLiteConstraintException:如何映射“无关系”在房间里有一个外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下实体:

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

}

公共类LogEntry {

@PrimaryKey(autoGenerate = true)
私人长ID;

私人长期servingId;

// ...
}

日志条目有一个服务和一些没有。添加一个日志条目
有一个服务可以正常工作,但是添加一个id = 0来表示无关系会导致
SQLiteConstraintException message


FOREIGN KEY约束失败



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

db.logEntryDao()。add(logEntry);

那么,我怎样才能表达一个日志条目在房间里没有服务的事实?

解决方案

您需要使用 Long 作为数据类型,并使用 servingId

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

db.logEntryDao()。add(logEntry);


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?

解决方案

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

这篇关于SQLiteConstraintException:如何映射“无关系”在房间里有一个外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆