Room persistent数据库 - 当没有与表相关的主键时,如何将项列表插入到DB中

j2e*_*nue 9 android android-room

我很难将列表项目放到房间里.列表项称为测量值,其类型为Measurement.列表项没有与数据库相关的主键.但如果有必要,我可以为ProductModel添加相同的主键.

这是我到目前为止:

@Entity(tableName = TABLE_NAME)
public class ProductModel {

    public static final String TABLE_NAME = "product";

    @PrimaryKey
    private int idProduct;

    private int idCategoryDefault;

    @Relation(parentColumn = "idProduct", entityColumn = "idProduct", entity = SortedAttribute.class)
    private List<SortedAttribute> sortedAttributes = null;
}

@Entity
public class SortedAttribute {

    @PrimaryKey
    private int idProduct;

    private String reference;

    @Embedded
    private List<Measurement> measurements = null; //****how do i get this into room ? its a LIST of measurements, not a measurement so calling Embedded i think wont work as it cant flatten it****/
}

public class Measurement {

    private String value;
    private String valueCm;

    public Measurement() {
    }
}
Run Code Online (Sandbox Code Playgroud)

Qua*_*yen 29

Embedded注释可以用于POJOEntity仅用于List,而不用于List.因此,Room在这种情况下,无法自动展平您的列表.
您可以使用TypeConverter转换List<MeasurementString(JSON格式),反之亦然.您可以使用任何JSON解析器库来支持它.例如,我使用Gson如下.

public class ProductTypeConverters {
    @TypeConverter
    public static List<Measurement> stringToMeasurements(String json) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<Measurement>>() {}.getType();
        List<Measurement> measurements = gson.fromJson(json, type);
        return measurements;
    }

    @TypeConverter
    public static String measurementsToString(List<Measurement> list) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<Measurement>>() {}.getType();
        String json = gson.toJson(list, type);
        return json;
    }
}

@Entity
@TypeConverters(ProductTypeConverter.class)
public class SortedAttribute {

    @PrimaryKey
    private int idProduct;

    private String reference;

    private List<Measurement> measurements = null; 
}
Run Code Online (Sandbox Code Playgroud)