Room persistent database - how to insert list of items into DB when it has no primary key related to table
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;
}
EDIT: Use a type converter
@Relation is what you are looking for.
https://developer.android.com/reference/android/arch/persistence/room/Relation.html
From the Room docs:
@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();
}
Note: Upon further research, Room does not quite support lists of objects that are INSIDE objects. I (and others) have opted to handle the lists separately. Room can handle lists of objects just fine as long as they aren't within an object; so as long as your items inside the list are related to your overall object you can recover the list.
So, you would actually @Ignore the list and just handle it in your Dao abstract class. I could not find the SO post's I found earlier that portray this.