删除会议室表时,Android Room FOREIGN KEY约束失败

时间:2019-07-18 07:40:26

标签: android android-room

我正在尝试删除RoomDatabase程序崩溃时的所有项目并引发此异常。

DAO

  @Query("DELETE FROM Room")
    public void deleteAll();

消息

@Entity(foreignKeys = @ForeignKey(entity = Room.class,
        parentColumns = "roomId",
        childColumns = "room_id"))
public class Message implements Parcelable {

    @NonNull
    @PrimaryKey
    private String messageId;
    @ColumnInfo(name = "room_id")
    private String room;
    private String message;
    private String userToConnect;
    private String userFullName;
    private String senderId;
    private String senderPhotoUrl;
    @TypeConverters(DateConverter.class)
    private Date creationTimestamp;
    private boolean read = false;

房间

@Entity(indices = {@Index(value = "lastUpdate")})
public class Room implements ProfilePhotoGenerator, Parcelable {

    @NonNull
    @PrimaryKey
    public String roomId;
    public String roomName;
    public String photoUrl;
    private String userToConnect;
    private String lastMessage;
    private int unReadCount=0;

你们有什么主意吗? 感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

经过测试,当我们尝试删除具有另一个现有表使用的外键的表时,看到android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed抛出。

在您的情况下,Message表具有引用Room表的外键(就像Message表需要Room表一样)

因此,要删除Room表而没有错误,您可以

1)首先删除Message表,然后再删除Room表(原因很容易理解)

2)使用CASCADE。使用它时,在删除id表中的某些Room之后,它将删除Message表中所有具有外键引用此id的记录。因此,如果删除所有Room表<=>,则删除所有Message

@Entity( foreignKeys = @ForeignKey(entity = Room.class,
         parentColumns = "roomId",
         childColumns = "room_id",
         onDelete = CASCADE  
))
public class Message implements Parcelable {