Android Room 构建问题:There are multiple good constructors

问题描述与处理策略

1、问题描述
java 复制代码
@Entity(tableName = "Car",
        indices = {
                @Index(name = "idx_car_carId_unique", value = {"carId"}, unique = true),
                @Index(name = "idx_car_carNum_unique", value = {"carNum"}, unique = true)
        })
public class Car extends BaseEntity {

    @ColumnInfo(name = "carId")
    @NonNull
    public Integer carId;

    @ColumnInfo(name = "carName")
    public String carName;

    @ColumnInfo(name = "carNum")
    @NonNull
    public String carNum;

    public Car() {
    }

    public Car(@NonNull Integer carId, String carName, @NonNull String carNum) {
        this.carId = carId;
        this.carName = carName;
        this.carNum = carNum;
    }

    @Override
    public String toString() {
        return "Car{" +
                "carId=" + carId +
                ", carName='" + carName + '\'' +
                ", carNum='" + carNum + '\'' +
                '}';
    }
}
  • 在 Room 中,上述定义的实体类,在构建时报如下错误

    There are multiple good constructors and Room will pick the no-arg constructor.
    You can use the @Ignore annotation to eliminate unwanted constructors.
    public class Car extends BaseEntity {
    ^

    翻译

    有多个构造函数,Room 将选择无参数构造函数。
    您可以使用 @Ignore 注释来消除不需要的构造函数。

2、问题原因
  1. Room 要求实体类必须有一个明确的构造函数,Room 优先选择无参构造函数

  2. 如果类中有其他构造函数,Room 会报错,因为它无法确定应该使用哪个构造函数

  3. 在代码中,Car 有两个构造函数,分别为无参构造函数 public Car() {} 和带参构造函数 public Car(@NonNull Integer carId, String carName, @NonNull String carNum),Room 无法确定应该使用哪个构造函数,因此报错

3、处理策略
  1. 使用 @Ignore 注解标记其他构造函数,例如,如果希望 Room 使用无参构造函数,可以使用 @Ignore 注解标记带参构造函数,告诉 Room 忽略它

  2. 或者,删除其他构造函数,例如,如果希望 Room 使用无参构造函数,可以删除带参构造函数

  • 这里选择使用 @Ignore 注解标记带参构造函数
java 复制代码
@Ignore
public Car(@NonNull Integer carId, String carName, @NonNull String carNum) {
    this.carId = carId;
    this.carName = carName;
    this.carNum = carNum;
}
相关推荐
每天一个秃顶小技巧2 分钟前
02.Golang 切片(slice)源码分析(一、定义与基础操作实现)
开发语言·后端·python·golang
serve the people1 小时前
解决osx-arm64平台上conda默认源没有提供 python=3.7 的官方编译版本的问题
开发语言·python·conda
柒七爱吃麻辣烫2 小时前
在Linux中安装JDK并且搭建Java环境
java·linux·开发语言
极小狐2 小时前
如何构建容器镜像并将其推送到极狐GitLab容器镜像库?
开发语言·数据库·机器学习·gitlab·ruby
多多*3 小时前
Java反射 八股版
java·开发语言·hive·python·sql·log4j·mybatis
正在走向自律3 小时前
从0到1:Python机器学习实战全攻略(8/10)
开发语言·python·机器学习
FY_20183 小时前
键盘输出希腊字符方法
开发语言
西西弗Sisyphus3 小时前
Python 处理图像并生成 JSONL 元数据文件 - 灵活text版本
开发语言·python
q567315234 小时前
Go语言多线程爬虫与代理IP反爬
开发语言·爬虫·tcp/ip·golang
Chandler244 小时前
Go语言即时通讯系统 开发日志day1
开发语言·后端·golang