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

Room数据库关联查询报错:StageWithReps需为@Entity或@DatabaseView

问题解决:Room关联类报错"The class must be either @Entity or @DatabaseView"

错误原因

在PresetWithStages的@Relation注解中,未明确指定关联的实体类,Room默认将泛型类型StageWithReps当作实体类处理,但StageWithReps只是用于封装关联数据的普通类,并非@Entity或@DatabaseView,因此触发错误。

解决方案

1. 修改PresetWithStages的@Relation注解

明确指定关联的实体为Stage.class,让Room知道通过preset_id关联Preset和Stage,并自动将Stage与对应的Rep数据组装为StageWithReps对象:

package com.example.intervalapp.relation;

import androidx.room.Embedded;
import androidx.room.Relation;
import com.example.intervalapp.entity.Preset;
import com.example.intervalapp.entity.Stage;
import java.util.List;

public class PresetWithStages {
  @Embedded
  private Preset preset;

  @Relation(
          parentColumn = "preset_id",
          entityColumn = "preset_id",
          entity = Stage.class // 新增此行,指定关联实体
  )
  private List<StageWithReps> stages;

  // Getters and Setters
  public Preset getPreset() {
    return preset;
  }

  public void setPreset(Preset preset) {
    this.preset = preset;
  }

  public List<StageWithReps> getStages() {
    return stages;
  }

  public void setStages(List<StageWithReps> stages) {
    this.stages = stages;
  }
}

2. 确认数据库类包含所有实体

确保你的Room数据库类(继承RoomDatabase)中,已将Preset、Stage、Rep都加入entities数组:

@Database(entities = {Preset.class, Stage.class, Rep.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract PresetDAO presetDAO();
    // 其他DAO接口声明
}

3. 修复Rep类的方法参数错误

Rep类中setRepDuration方法的参数类型为int,但字段类型是float,会导致类型不匹配,修改为:

public void setRepDuration(float repDuration) {
    this.repDuration = repDuration;
}

验证

完成上述修改后,重新编译项目,getAllPresets()方法应该能正常返回包含层级关联数据的LiveData<List<PresetWithStages>>,每个Preset包含对应的StageWithReps列表,次数型阶段会附带对应的Rep数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:22:37