Room 编译问题 - 列引用外键,但它不是索引的一部分

Fer*_*ain 7 java android android-sqlite android-room

我是 Android 应用程序开发的新手,正在创建一个具有存储位置的 Trips 的应用程序。

我收到编译错误:“trip_Id 列引用外键,但它不是索引的一部分。每当修改父表时,这可能会触发全表扫描,因此强烈建议您创建一个覆盖此列的索引。”

我有两张表:行程和位置。

我尝试在各自的类中对 tripId 和 locationId 建立索引,但这并不能解决问题。

一次旅行有它的 ID (PK)、标题、描述和优先级。

位置具有该地点的 locationId (PK)、tripId(FK)、locationName 和 LatLng。

@Entity(tableName = "location_table",
        foreignKeys = @ForeignKey(entity = Trip.class, parentColumns = "location_Id", childColumns = "trip_Id"),
        indices = {@Index(value = {"locationId"}, unique = true)})
public class Location {

    @PrimaryKey(autoGenerate = true)
    private int locationId;

    @ColumnInfo (name = "trip_Id")
    private int tripId;

    private String locationName;

    @TypeConverters(LatLngConverter.class)
    private LatLng latLng;


@Entity(tableName = "trip_table", indices = {@Index(value = {"id"}, unique = true)})

public class Trip {

    @PrimaryKey(autoGenerate = true) // with each new row SQLite will automatically increment this ID so it will be unique
    @ColumnInfo (name = "location_Id")
    private int id;

    private String title;

    private String description;

    private int priority;

Run Code Online (Sandbox Code Playgroud)

我似乎无法找出问题所在

Mik*_*keT 7

该消息是警告,还会有其他错误(请参阅第二条建议行)。例如

在此输入图像描述

使用indices = {@Index(value = {"locationId"}, unique = true),@Index(value = {"trip_Id"})})应该克服该警告。

然而,不需要在locationId上有一个(额外的)索引,因为它已经被索引为主键(这会浪费而且效率低下)。所以建议您使用:-

indices = {@Index(value = {"trip_Id"})})
Run Code Online (Sandbox Code Playgroud)

我相信您的总体问题是您指的是该列的对象变量名称,如果您有那么@ColumnInfo(name ="????")您应该指的是给定名称

  • IE ????是基础表中的列名。

您还应该在 Trip 中使用location_Id而不是id :-

@Entity(tableName = "trip_table", indices = {@Index(value = {"location_Id"}, unique = true)})
Run Code Online (Sandbox Code Playgroud)