构建Room数据库时触发多类报错,寻求问题排查与解决方案
问题分析与修复方案
以下是你遇到的每个错误对应的原因和修复步骤:
1. error: Entity class must be annotated with @Entity & no such table: userUi
原因:Database类的entities数组错误引用了UserDao.class,Room要求这里配置的是实体类(而非DAO接口)。
修复:修改Database的实体配置:
@androidx.room.Database( entities = {User.class}, // 替换为User实体类 version = 6 )
2. error: Entities and POJOs must have a usable public constructor
原因:User类的构造函数缺少user_id字段的参数,导致Room无法匹配所有字段;同时autoGenerate = true不能用于String类型的主键(仅支持int/long)。
修复:
- 方案一:添加无参构造函数
public User() { // 空构造函数 }
- 方案二:补充现有构造函数的
user_id参数
public User(String id, String agency_id, String user_id, String user_code, String password, String csc_authenticable, String equipment_type, String equipment_subtype, String profile, String user_name) { this.id = id; this.agency_id = agency_id; this.user_id = user_id; this.user_code = user_code; this.password = password; this.csc_authenticable = csc_authenticable; this.equipment_type = equipment_type; this.equipment_subtype=equipment_subtype; this.profile = profile; this.user_name = user_name; }
3. error: An entity must have at least 1 field annotated with @PrimaryKey & SQL语法错误
原因:User类同时给id和user_code标记了@PrimaryKey,Room不允许单个实体有多个独立主键;且String类型字段不能使用autoGenerate = true。
修复:
- 保留
id为主键,修改为int类型并保留自动生成,移除user_code的@PrimaryKey:
@PrimaryKey(autoGenerate = true) private int id; // 改为int类型 @ColumnInfo(name="user_code") @Unique // 若需要user_code唯一,添加此注解 private String user_code;
4. getIds()返回类型不匹配
原因:getIds()返回List<Byte>,但id字段类型不匹配(修复后为int)。
修复:调整返回类型:
@Query("SELECT DISTINCT id FROM userUi") List<Integer> getIds();
5. getCountByAgencyId()参数类型不匹配
原因:方法参数int agency_id与User类中agency_id的String类型冲突。
修复:修改参数类型为String:
@Query("SELECT COUNT(*) FROM userUi WHERE agency_id=:agency_id") Integer getCountByAgencyId(String agency_id);
内容的提问来源于stack exchange,提问作者Manuel Lucas
相关产品推荐
相关产品推荐

