【发布时间】:2017-11-18 17:26:28
【问题描述】:
在Android room persistent library 中,如何将整个模型对象插入到本身具有另一个列表的表中。
让我告诉你我的意思:
@Entity(tableName = TABLE_NAME)
public class CountryModel {
public static final String TABLE_NAME = "Countries";
@PrimaryKey
private int idCountry;
private List<CountryLang> countryLang = null;
public int getIdCountry() {
return idCountry;
}
public void setIdCountry(int idCountry) {
this.idCountry = idCountry;
}
public String getIsoCode() {
return isoCode;
}
public void setIsoCode(String isoCode) {
this.isoCode = isoCode;
}
/**
here i am providing a list of coutry information how to insert
this into db along with CountryModel at same time
**/
public List<CountryLang> getCountryLang() {
return countryLang;
}
public void setCountryLang(List<CountryLang> countryLang) {
this.countryLang = countryLang;
}
}
我的 DAO 如下所示:
@Dao
public interface CountriesDao{
@Query("SELECT * FROM " + CountryModel.TABLE_NAME +" WHERE isoCode =:iso_code LIMIT 1")
LiveData<List<CountryModel>> getCountry(String iso_code);
@Query("SELECT * FROM " + CountryModel.TABLE_NAME )
LiveData<List<CountryModel>> getAllCountriesInfo();
@Insert(onConflict = REPLACE)
Long[] addCountries(List<CountryModel> countryModel);
@Delete
void deleteCountry(CountryModel... countryModel);
@Update(onConflict = REPLACE)
void updateEvent(CountryModel... countryModel);
}
当我调用database.CountriesDao().addCountries(countryModel); 时,我收到以下房间数据库编译错误:
错误:(58, 31) 错误:无法弄清楚如何将此字段保存到数据库中。您可以考虑为其添加类型转换器。
应该有另一个名为 CountryLang 的表吗?如果是这样,如何告诉空间在插入语句中连接它们?
CountryLang 对象本身如下所示:
public class CountryLang {
private int idCountry;
private int idLang;
private String name;
public int getIdCountry() {
return idCountry;
}
public void setIdCountry(int idCountry) {
this.idCountry = idCountry;
}
public int getIdLang() {
return idLang;
}
public void setIdLang(int idLang) {
this.idLang = idLang;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
响应如下所示:
"country_lang": [
{
"id_country": 2,
"id_lang": 1,
"name": "Austria"
}
]
对于每个国家/地区,因此这里不会超过一项。我很乐意为 country_lang 列表中的一项设计它。所以我可以为 country_lang 制作一个表格,然后将其链接到 CountryModel。但如何?我可以使用外键吗?我希望我不必使用平面文件。所以你说我必须将它存储为 json ?是否建议不要临时使用房间?改用什么?
【问题讨论】:
-
忘记了 temporaray 的空间,那么您想在 CountryModel 中以哪种格式存储 countryLang 字段?是否要以逗号分隔存储?
-
如果您确定只有一项,那么您应该使用对象而不是数组。因为如果您使用对象,您可以使用
@Embedded注释轻松地将 countryLang 类嵌入 CountryModel 中 -
如果你不能改变json那么你应该使用外键关系。
-
感谢您的回复。关于@embedded 的好主意。你知道我是否可以使用嵌入列表吗?这个模型来自一个休息服务响应。它以 json 形式返回,然后我使用 gson 将其转换为 java 对象。所以我不必将其保留为 List 类型。正如您在我关于 country_lang 结构的声明中所见,json 将其作为列表对象。在这种情况下如何使用外键。
-
可以使用
@Relation注解。查看this answer
标签: android android-room