You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Room使用@PrimaryKey(autoGenerate = true)时出现找不到setter编译错误

解决Room自动生成主键时"Cannot find setter for field"错误

这个问题我之前也碰到过,核心原因是Room处理自动生成的主键时,需要能正确初始化或设置字段值,仅仅添加setter方法可能还满足不了它的要求。下面给你几种可行的解决办法:

方法一:添加全参构造函数并忽略自定义构造函数

Room需要一个包含所有字段的构造函数来创建实体实例,我们可以添加带id参数的全参构造函数,同时用@Ignore注解标注业务代码中使用的无id构造函数:

@Entity(tableName = "word_table")
public class Word {
    @PrimaryKey(autoGenerate = true)
    private int id;
    @NonNull
    private String word;

    // 供Room内部使用的全参构造函数
    public Word(int id, @NonNull String word) {
        this.id = id;
        this.word = word;
    }

    // 供业务代码调用的构造函数,用@Ignore让Room忽略它
    @Ignore
    public Word(@NonNull String word) {
        this.word = word;
    }

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getWord() { return this.word; }
}

方法二:将id字段设为public

直接把id字段的访问修饰符改为public,这样Room可以直接访问该字段,不需要依赖setter方法:

@Entity(tableName = "word_table")
public class Word {
    @PrimaryKey(autoGenerate = true)
    public int id;
    @NonNull
    private String word;

    public Word(@NonNull String word) {
        this.word = word;
    }

    public String getWord() { return this.word; }
}

方法三:用Lombok简化代码(可选)

如果你的项目已经引入Lombok,可以用注解自动生成构造函数和setter方法,让代码更简洁:

@Entity(tableName = "word_table")
@NoArgsConstructor
@AllArgsConstructor
@Setter
public class Word {
    @PrimaryKey(autoGenerate = true)
    private int id;
    @NonNull
    private String word;

    // 自定义构造函数,需用@Ignore标注
    @Ignore
    public Word(@NonNull String word) {
        this.word = word;
    }

    public int getId() { return id; }
    public String getWord() { return this.word; }
}

简单来说:Room需要能访问实体类的所有字段,要么提供全参构造函数,要么让字段可直接访问,这样它才能正确处理自动生成的主键值。

内容的提问来源于stack exchange,提问作者user3576118

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:41:42