安卓房间中的实体继承



我有一个父类队列,其中包含以下字段:

  1. 名字
  2. 类型
  3. 地位

根据类型,我将 Queue 分解为其他子类,每个子类都有自己的额外字段。例如:

ProductionQueue extends Queue { startDate, endDate }
ShippingQueue extends Queue { shippingDate, shippingAgent }
...

我已经在 android studio 中创建了 Queue 作为基类,并从中扩展了我的子类,但代码无法编译并抱怨缺少字段(子类字段)。下面是一个示例:

@Entity(tableName = "queue")
public class Queue {
int id;
String name;
int type;
int status;
}
@Entity
public class ProductionQueue extends Queue {
String startDate;
String endDate
}
@Dao
public interface ProductionQueueDao extends BaseDao<ProductionQueue> {
@Query("SELECT * FROM queue WHERE id = :queueID")
LiveData<List<ProductionQueue>> findByID(Long queueID);
}

在编译时,我收到:错误:查询返回的列在com.example.room.ProductionQueue中没有字段[startDate,endDate],即使它们被注释为非null或原始。查询返回的列:[id,名称,类型,状态]。

[id,name,type,status]来自父类,而[startDate, endDate]是子类字段。

在我的应用程序中,我只会列出队列名称、类型和状态,并且我希望将队列数据保存在一个表中以便快速查询。

我可以为单个子类创建子表并使用关系,但如果 Room 允许继承,所有这些都可以轻松避免。房间是否支持这种继承,如果是,我怎样才能让它工作?

谢谢。

问题是您正在尝试从表queue中检索生产队列,该表不包含有关生产队列所需日期的信息。

要解决此问题,请为生产队列表定义一个名称:

@Entity(tableName = "production_queue")
public class ProductionQueue extends Queue {
...
}

然后,更改查询以从正确的表中检索行:

// Retrieving rows from "production_queue", not from "queue"
@Query("SELECT * FROM production_queue WHERE id = :queueID")
LiveData<List<ProductionQueue>> findByID(Long queueID);

这样,返回的行将包括字段startDateendDate

最新更新