android - 如何嵌入不直接相关的 Room 实体?
问题描述
我有三个基本实体来表示我的 Room 数据库中的表:Country、State和City。
为了在一个州内嵌入城市列表,我创建了一个名为StateWithCities的 POJO :
package org.example.roomtest;
import java.util.List;
import androidx.room.Embedded;
import androidx.room.Relation;
public class StateWithCities {
@Embedded
public State state;
@Relation(
parentColumn = "_id", // This is the `states`.`_id` column.
entityColumn = "state_id" // This is the `cities`.`state_id` column.
)
public List<City> cities;
}
然后我可以从我的StateDao界面中的查询返回:
@Query("SELECT * FROM `states`")
LiveData<List<StateWithCities>> getAllStatesWithCities();
但是,我现在想在我的CountryDao界面中创建一个查询,该查询可以返回与某个国家/地区关联的城市。
(国家和城市通过states
表格相关联。所以,正如您所料,cities
.state_id
与states
.相关,_id
并且states
.country_id
与countries
. _id
. 相关)
所以我创建了一个CountryWithStatesWithCities POJO:
package org.example.roomtest;
import java.util.List;
import androidx.room.Embedded;
import androidx.room.Relation;
public class CountryWithStatesWithCities {
@Embedded
public Country country;
@Relation(
parentColumn = "_id", // This is the `country`.`_id` column.
entityColumn = "country_id" // This is the `states`.`country_id` column.
)
public List<StateWithCities> stateWithCities;
}
在这一点上,一切都编译得很好。但是当我将此查询添加到CountryDao时:
@Query("SELECT * FROM `countries`")
LiveData<List<CountryWithStatesWithCities>> getAllCountriesWithStatesWithCities();
我得到这些引用我的两个类的编译错误,上面:
> ...StateWithCities.java:7: error: The class must be either @Entity or @DatabaseView.
> public class StateWithCities {
> ^
和
> ...CountryWithStatesWithCities.java:16: error: Cannot find the child entity column `country_id` in org.team_love.shapethefuture.roomtest.StateWithCities. Options:
> public List<StateWithCities> stateWithCities;
> ^
这些错误似乎告诉我我的CountryDao接口需要引用实体(或 DatabaseViews)而不是 POJO。那么,解决我的要求的正确方法是什么:如何嵌入不直接相关的 Room 实体?
解决方案
你需要设置你的实体类显式描述CountryWithStatesWithCities
,因为 Room 有一个问题来从上下文中推断它:
public class CountryWithStatesWithCities {
@Embedded
public Country country;
@Relation(
entity = State.class, <- this should be added explicitly
parentColumn = "_id", // This is the `country`.`_id` column.
entityColumn = "country_id" // This is the `states`.`country_id` column.
)
public List<StateWithCities> stateWithCities;
}
推荐阅读
- ubuntu - 删除 SSL 证书并在 ubuntu 16 上使用 Letsencrypt NGINX 生成证书的建议
- java - 如何为创建表和添加值的方法编写测试用例
- python - 如何遍历 Spark RDD 以评估嵌套元组中的每个元素并将结果附加到原始 RDD?
- ios - Xcode 版本中的 lldb-rpc-server 是 10.1?
- logstash - 当日志源是文件时,Logstash 如何判断日志文件中哪一行是新的?
- laravel - 错误:流明使用本地时间,同时保存时间戳记录
- ruby-on-rails - 未定义的方法`price_workshops_attributes' - Ruby on rails
- python - 如何按升序排列 Z3 生成的模型中的值?
- swift - 即使将 Json 附加到数组中,数组也会打印空白
- powershell - Powershell 哈希表调用外部命令