Room Database编译错误:Field具有非唯一列名

时间:2018-04-27 11:42:08

标签: java android database android-room

我在班级的某些字段上收到此错误

  

错误:字段具有非唯一列名称

@Entity(tableName = "Team", foreignKeys = {
    @ForeignKey(entity = Group.class, parentColumns = "id", childColumns = "groupId")},
    indices = {@Index("groupId")})
public class Team {

    @PrimaryKey
    private long id;
    private long groupId;
    @SerializedName("Team")
    private String name;
    private String englishName;
    @SerializedName("Played")
    private int played;
    @SerializedName("Victories")
    private int win;
    @SerializedName("Draws")
    private int draw;
    @SerializedName("Defeats")
    private int defeat;
    @SerializedName("Made")
    private int goalFor;
    @SerializedName("Let")
    private int goalAgainst;
    @SerializedName("Diff")
    private int goalDiff;
    @SerializedName("Points")
    private int points;

    public Team() {

    }

    /* getter and setter methods */
}

例如,我在“win”,“draw”,“groupId”上收到此错误。但不是“id”或“name”。正如您所看到的那样,这是一个编译错误,除了标题中的句子外,它不再提供有关错误的信息。

修改:我尝试更改变量名称但不起作用。

编辑:“获胜”的getter和setter方法,其他方法看起来与此完全相同。

public int getWin() {
    return win;
}

public void setWin(int win) {
    this.win = win;
}

2 个答案:

答案 0 :(得分:2)

您需要添加一个前缀,以避免重复的列名。根据官方文档:

前缀 字符串前缀() 指定前缀,以在嵌入字段中的字段列名之前添加

对于上面的示例,如果我们写过:

  

@Embedded(prefix =“ foo_”)坐标坐标;

https://developer.android.com/reference/android/arch/persistence/room/Embedded.html#prefix()

答案 1 :(得分:0)

我找到了一个解决方案(好吧,实际上并不是解决方案)。 我有另一个名为“Group”的实体:

@Entity
public class Group {

    @PrimaryKey
    private long id;
    private String name;
    @Embedded
    private List<Team> teams;

    public Group() {

    }

    public Group(String name) {
        this.name = name;
    }

    /* getter and setter methods */

事实证明,带有“嵌入式”注释的变量“团队”是我的问题的根源。当我删除它,代码工作正常。如果有人能向我解释我做错了什么(或者我做错了吗?)我会很感激。

修改:找到与此问题相关的一些链接。

Android Room @Embedded annotation compilation fails for @NonNull annotated constructor parameters of a POJO defined in a library module

https://github.com/googlesamples/android-architecture-components/issues/318

相关问题