Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

android - Room persistent database - how to insert list of items into DB when it has no primary key related to table

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() {
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...