A persistent database - how to insert a list of items in a database if it does not have a primary key associated with the table

I find it difficult to find the list item in the room. The list item is called dimensions and its type is Measurement. the list item does not have a primary key to be associated with the database. but I have no problem adding the same primary key for ProductModel if necessary.

Here is what I still have:

@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() {
    }
}
+8
source share
2 answers

Embedded POJO Entity, . , Room .
TypeConverter List<Measurement String ( JSON) . 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; 
}
+23

@ , .

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 , ; , , .

, @ Dao. , , .

:

0

Source: https://habr.com/ru/post/1680377/


All Articles