Room 持久数据库 - 当没有与 table 相关的主键时如何将项目列表插入数据库

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

我很难将列表项放入房间。列表项称为测量,其类型为测量。列表项没有与数据库相关的主键。 但如有必要,我可以为 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() {
    }
}

Embedded 注释只能用于 POJOEntity,不能用于列表。因此,在这种情况下,Room 无法自动展平您的列表。
您可以使用 TypeConverterList<Measurement> 转换为 StringJSON 格式),反之亦然。您可以使用任何 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; 
}

编辑:使用类型转换器

@Relation 就是你要找的。

https://developer.android.com/reference/android/arch/persistence/room/Relation.html

来自 Room 文档:

@Entity
public class Pet {
     @ PrimaryKey
     int petId;
     String name;
 }
 public class UserNameAndAllPets {
   public int userId;
   public String name;
   @Relation(parentColumn = "petId", entityColumn = "userId")
   public List<Pet> pets;
 }

 @Dao
 public interface UserPetDao {
     @Query("SELECT petId, name from User")
     public List<UserNameAndAllPets> loadUserAndPets();
 }

注意:经过进一步研究,Room 不太支持 INSIDE 对象列表。我(和其他人)选择单独处理这些列表。只要对象不在对象内,Room 就可以很好地处理对象列表;所以只要列表中的项目与您的整体对象相关,您就可以恢复列表。

因此,您实际上会@Ignore 列表并在您的 Dao 摘要中处理它 class。我找不到我之前找到的描述此内容的 SO post。