在Android 房间持久库中,如何将整个 Model 对象插入到本身具有另一个列表的表中。
让我告诉你我的意思:
@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 ?是否建议不要临时使用房间?改用什么?