Android Room FOREIGN KEY 约束在删除房间表时失败

ksg*_*rkn 2 android android-room

我试图删除 RoomDatabase 程序崩溃中的所有项目并引发此异常。

DAO

  @Query("DELETE FROM Room")
    public void deleteAll();
Run Code Online (Sandbox Code Playgroud)

信息

@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;
Run Code Online (Sandbox Code Playgroud)

房间

@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;
Run Code Online (Sandbox Code Playgroud)

你们有什么想法吗?谢谢你的帮助。

Pha*_*inh 5

经过测试,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 {
Run Code Online (Sandbox Code Playgroud)