会议室持久数据库-当数据库没有与表相关的主键时,如何将项目列表插入数据库 [英] Room persistent database - how to insert list of items into DB when it has no primary key related to table

查看:69
本文介绍了会议室持久数据库-当数据库没有与表相关的主键时,如何将项目列表插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难将清单项放到房间里.该列表项称为度量",其类型为度量".列表项没有与数据库相关的主键. 但是如果有必要,我可以为ProductModel添加相同的主键没有问题.

I am having a hard time getting a list item into room. the list item is called measurements and its of type Measurement. the list item has no primarykey that would be related to the database. but i have no problem adding the same primary key for the ProductModel if necessary.

这是我到目前为止所拥有的:

Here is what i have so far:

@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() {
    }
}

推荐答案

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

Embedded annotation can be used on a POJO or Entity only, not for a List. So, Room can not automatically flatten your list in this case.
You can use TypeConverter to convert List<Measurement into String(in JSON format) and vise versa. You can use any JSON parser library to support it. For example, I use Gson as following.

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; 
}

这篇关于会议室持久数据库-当数据库没有与表相关的主键时,如何将项目列表插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆