如何在Room Dao函数中更新实体的TypeConverted列

sky*_*eek 6 android typeconverter kotlin android-database android-room

我有一个@Entity,它包含一个变量(自定义对象列表)以及该表的其他字段.我能够从这个实体插入,获取和删除.

但我在更新实体时面临一个问题:

我想更新该特定字段,该字段包含表中的自定义对象列表,但在编译时会抛出错误:

error: Query method parameters should either be a type that can be converted into a
database column or a List / Array that contains such type. You can consider adding a Type Adapter for this.
Run Code Online (Sandbox Code Playgroud)

我可以更新完整的行对象,但问题在于更新此单个字段.我在我的@Database类上使用TypeConverters但是我尝试在Dao和更新函数本身上使用它们但是它报告了相同的错误.

有人可以帮我更新行中的这个特定字段,我不想提供这个实体的完整对象来实现这一点.

我的实体是:

@Entity data class TableName(
    @PrimaryKey
    var id: String = "",
    @SerializedName("varOne")
    @Expose
    var varOne: List<CustomObjects>? = null)
Run Code Online (Sandbox Code Playgroud)

更新方法是这样的:

@TypeConverters(MyTypeConverters.VarOneListTypeConverters::class)
@Query("Update TableName SET varOne = :varOneList")
abstract fun updateTableName(varOneList: List<CustomObjects>)
Run Code Online (Sandbox Code Playgroud)

小智 2

理想情况下,您应该尝试将其建模为与 的单独表CustomObject和 的主键的外键引用的关系TableName。但是您仍然可以为该类型编写转换器List<CustomObject>。Room 仅理解Sqlite 数据类型,任何其他类型都需要转换为 room 理解的其中一种类型。他们提供了TypeConverter相同的注释。如果您使用Gson序列化CustomObject那么您可以使用以下转换器。代码是不言自明的

public class Converters {
   @TypeConverter
   public static ArrayList<String> fromString(String value) {
      Type listType = new TypeToken<ArrayList<CustomObject>>() {}.getType();
      return new Gson().fromJson(value, listType);
   }
   @TypeConverter
   public static String fromArrayList(ArrayList<CustomObject> list) {
      Gson gson = new Gson();
      String json = gson.toJson(list);
      return json;
   }
}
Run Code Online (Sandbox Code Playgroud)

你只需要把这个转换器添加到你的Database类中

@TypeConverters(Converters::class) 
abstract class YourDatabase extends RoomDatabase
Run Code Online (Sandbox Code Playgroud)