Android Room FOREIGN KEY约束失败(代码787)

时间:2018-06-06 21:02:00

标签: android sql orm android-room android-orm

我想在Android Room中用两个外键创建一个数据库。每当我尝试将轨道插入数据库时​​,程序就会崩溃,并说“外键代价是失败的(代码787)”。也许有人知道为什么,可以帮助我。

@Entity(foreignKeys = {@ForeignKey(
    entity = Kategorie.class,
    childColumns = "kategorieFremdschluessel",
    parentColumns = "kategorieID",
    onUpdate = ForeignKey.CASCADE,
    onDelete = ForeignKey.CASCADE
    ),
    @ForeignKey(
            entity = Playlist.class,
            childColumns = "playlistFremdschluessel",
            parentColumns = "uuid",
            onUpdate = ForeignKey.CASCADE,
            onDelete = ForeignKey.CASCADE
    )
 })

public class Track {

@PrimaryKey(autoGenerate = true)
private int uid;

private String trackTitel;
private String playlistName;
private String jsonObjectString;
private int kategorieFremdschluessel;
private int playlistFremdschluessel;

@Ignore
public Track(String trackTitel, String playlistName, String jsonObjectString) {
    this.trackTitel = trackTitel;
    this.playlistName = playlistName;
    this.jsonObjectString = jsonObjectString;
}

public Track(String trackTitel, String jsonObjectString) {
    this.trackTitel = trackTitel;
    this.jsonObjectString = jsonObjectString;
}
//Getter and Setter

@Dao

TrackDao

public interface TrackDao {

@Query("SELECT * FROM Track WHERE playlistName LIKE :playlist")
List<Track> getAllTracks(String playlist);

@Query("SELECT * FROM Track WHERE kategorieFremdschluessel = :kategorieFremdschluessel")
List<Track> loadAllKategorieTracks(int kategorieFremdschluessel);

@Query("SELECT * FROM Track WHERE playlistFremdschluessel = :playlistFremdschluessel")
List<Track> loadAllPlaylistTracks(int playlistFremdschluessel);

@Insert
void insertAll(List<Track> trackList);

@Insert
void insertOne(Track track);

@Update
void updateOne(Track track);

@Delete
void delete(Track track);
}

“Kategorie”和“播放列表”也是数据库中的表格。

@Entity
public class Playlist{


@PrimaryKey(autoGenerate = true)
private int uuid;

@ColumnInfo(name = "name")
private String name;

Kategorie

@Entity
public class Kategorie {



@PrimaryKey(autoGenerate = true)
private int kategorieID;


@ColumnInfo(name = "name")
private String name;

2 个答案:

答案 0 :(得分:4)

您需要在表KategoriePlaylist中添加与您要插入的Track相同的foreign key行。

答案 1 :(得分:0)

发生此错误的另一个原因是,由于我的情况下互联网上所有可用的解决方案似乎都是徒劳的,因此花费了我很多时间。

如果将父表的 rowId 用作 parentColumn键,则不能使用外键约束。

按照SQLite documentation on Foreign Keys

  

父键是父表中的一列或一组列   外键约束所指的。这是正常的,但不是   始终是父表的主键。父键必须是   父表中的一个或多个命名列,而不是