64

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 ?是否建议不要临时使用房间?改用什么?

4

7 回答 7

100

您可以使用TypeConverterGSON 轻松插入带有列表对象字段的类,

public class DataConverter {

    @TypeConverter
    public String fromCountryLangList(List<CountryLang> countryLang) {
        if (countryLang == null) {
            return (null);
        }
        Gson gson = new Gson();
        Type type = new TypeToken<List<CountryLang>>() {}.getType();
        String json = gson.toJson(countryLang, type);
        return json;
    }

    @TypeConverter
    public List<CountryLang> toCountryLangList(String countryLangString) {
        if (countryLangString == null) {
            return (null);
        }
        Gson gson = new Gson();
        Type type = new TypeToken<List<CountryLang>>() {}.getType();
        List<CountryLang> countryLangList = gson.fromJson(countryLangString, type);
        return countryLangList;
    }
 }

接下来,将@TypeConverters 注解添加到 AppDatabase 类

    @Database(entities = {CountryModel.class}, version = 1)
    @TypeConverters({DataConverter.class})
    public abstract class AppDatabase extends RoomDatabase {
      public abstract CountriesDao countriesDao();
    }

有关Room 中 TypeConverters 的更多信息,请查看我们的博客和官方文档

于 2018-01-15T10:08:00.083 回答
38

这是 Aman Gupta 在 Kotlin 中的转换器,适用于喜欢复制粘贴的懒惰 Google 员工:

class DataConverter {

    @TypeConverter
    fun fromCountryLangList(value: List<CountryLang>): String {
        val gson = Gson()
        val type = object : TypeToken<List<CountryLang>>() {}.type
        return gson.toJson(value, type)
    }

    @TypeConverter
    fun toCountryLangList(value: String): List<CountryLang> {
        val gson = Gson()
        val type = object : TypeToken<List<CountryLang>>() {}.type
        return gson.fromJson(value, type)
    }
}

此外,将 @TypeConverters 注释添加到 AppDatabase 类

@Database(entities = arrayOf(CountryModel::class), version = 1)
@TypeConverters(DataConverter::class)
abstract class AppDatabase : RoomDatabase(){
    abstract fun countriesDao(): CountriesDao
}

于 2018-05-09T15:10:36.073 回答
13

正如 Omkar 所说,你不能。@Ignore在这里,我根据文档描述了为什么您应该始终使用注释: https ://developer.android.com/training/data-storage/room/referencing-data.html#understand-no-object-references

您将处理表中的 Country 对象以仅检索其权限的数据;Languages 对象将转到另一个表,但您可以保留相同的 Dao:

  • Country和Languages对象是独立的,只需在Language实体(countryId,languageId)中定义更多字段的primaryKey。当活动线程为 Worker 线程时,可以将它们串联保存在 Repository 类中:对 Dao 的两次插入请求。
  • 要加载 Country 对象,您需要使用 countryId。
  • 要加载相关的 Languages 对象,您已经拥有 countryId,但您需要先加载该国家/地区,然后再加载语言,以便您可以在父对象中设置它们并仅返回父对象。
  • 当您加载国家/地区时,您可能可以在 Repository 类中连续执行此操作,因此您将同步加载国家和语言,就像您在服务器端所做的那样!(没有 ORM 库)。
于 2017-12-29T17:59:36.207 回答
8

你不能。

实现这一点的唯一方法是使用@ForeignKey约束。如果您仍想将对象列表保留在父 POJO 中,则必须使用@Ignore或提供@TypeConverter

有关更多信息,请关注此博客文章:-

https://www.bignerdranch.com/blog/room-data-storage-on-android-for-everyone/

和示例代码: -

https://github.com/googlesamples/android-architecture-components

于 2017-07-10T18:30:10.493 回答
5

我也有类似的情况。为了解决这个问题,我使用TypeConvertsMoshi将列表解析为字符串。

请按照以下步骤操作:

1 - 创建一个带有转换器的类。

class Converters {

    private val moshi = Moshi.Builder().build()
    private val listMyData : ParameterizedType = Types.newParameterizedType(List::class.java, MyModel::class.java)
    private val jsonAdapter: JsonAdapter<List<MyModel>> = moshi.adapter(listMyData)

    @TypeConverter
    fun listMyModelToJsonStr(listMyModel: List<MyModel>?): String? {
        return jsonAdapter.toJson(listMyModel)
    }

    @TypeConverter
    fun jsonStrToListMyModel(jsonStr: String?): List<MyModel>? {
        return jsonStr?.let { jsonAdapter.fromJson(jsonStr) }
    }
}

2 - 在 RoomDatabase 类中使用转换器定义类。

@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {...}

...您将 @TypeConverters 注释添加到 AppDatabase 类,以便 Room 可以使用您为该 AppDatabase 中的每个实体和 DAO 定义的转换器...

...有时,您的应用程序需要使用您希望将其值存储在单个数据库列中的自定义数据类型。要添加对自定义类型的这种支持,您需要提供一个TypeConverter,它将自定义类与 Room 可以保留的已知类型相互转换。

参考:

Moshi 解析列表 (Kotlin)

如何解析列表?#78(由杰克沃顿回答)

使用类型转换器(官方文档)

莫西图书馆

于 2020-04-21T15:47:33.567 回答
2

我做了类似于@Daniel Wilson 的事情,但是,我使用了Moshi ,因为它是建议的库。要了解有关 Moshi 和 Gson 之间区别的更多信息,我建议您观看此视频

就我而言,我必须List<LatLng>Room数据库中存储一个。如果您不知道LatLng用于处理地理坐标,即纬度和经度。为此,我使用了以下代码:

class Converters {

    private val adapter by lazy {
        val moshi = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
        val listMyData = Types.newParameterizedType(List::class.java, LatLng::class.java)
        return@lazy moshi.adapter<List<LatLng>>(listMyData)
    }

    @TypeConverter
    fun toJson(coordinates: List<LatLng>) : String {
        val json = adapter.toJson(coordinates)
        return json
    }

    @TypeConverter
    fun formJson(json: String) : List<LatLng>? {
        return adapter.fromJson(json)
    }
}
于 2021-04-19T17:13:11.467 回答
0

为自定义对象字段添加@Embedded(请参阅以下示例)

//this class refers to pojo which need to be stored
@Entity(tableName = "event_listing")
public class EventListingEntity implements Parcelable {

    @Embedded  // <<<< This is very Important in case of custom obj 
    @TypeConverters(Converters.class)
    @SerializedName("mapped")
    public ArrayList<MappedItem> mapped;

    //provide getter and setters
    //there should not the duplicate field names
}

//add converter so that we can store the custom object in ROOM database
public class Converters {
    //room will automatically convert custom obj into string and store in DB
    @TypeConverter
    public static String 
    convertMapArr(ArrayList<EventListingEntity.MappedItem> list) {
    Gson gson = new Gson();
    String json = gson.toJson(list);
    return json;
    }

  //At the time of fetching records room will automatically convert string to 
  // respective obj
  @TypeConverter
  public static ArrayList<EventsListingResponse.MappedItem> 
  toMappedItem(String value) {
    Type listType = new 
     TypeToken<ArrayList<EventsListingResponse.MappedItem>>() {
    }.getType();
    return new Gson().fromJson(value, listType);
  }

 }

//Final db class
@Database(entities = {EventsListingResponse.class}, version = 2)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
    ....
}
于 2018-05-18T14:29:38.227 回答