17

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

2 回答 2

36

Embedded注释可以用于POJOEntity仅用于列表,不能用于列表。因此,Room在这种情况下不能自动展平您的列表。
您可以使用TypeConverter转换List<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; 
}
于 2017-06-29T06:17:49.757 回答
4

编辑:使用类型转换器

@Relation 是您正在寻找的。

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

来自房间文档:

@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 抽象类中处理它。我找不到我之前找到的描述这一点的 SO 帖子。

于 2017-11-07T18:49:17.090 回答