Hanna :
Help please! I have a problem only with insert pojos in databes with relation one-to-many. I have pojos and misunderstood how insert all list in database???
@Entity
data class Street(
@PrimaryKey(autoGenerate = true)
var id: Int = 0
) {
@Ignore
var houses: List<House>? = listOf()
}
@Entity
data class House(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var streetId: Int
) {
@Ignore
var flats: List<Flat>? = listOf()
}
@Entity
data class Flat(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var houseId: Int
)
Please help me guys!
Alex Grebennikov :
You need to remove @Ignore
annotations and use type converters.
IMHO it is better to save only the ids of the pojo and not the whole object e.g.
@Entity
data class House(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var streetId: Int,
var flatIds: List<Int>? = listOf()
)
And when you need all those flats just query the FlatDao by those ids
If you still want to save whole object you can convert it to Gson and then convert back
class YourObjectConverter {
@TypeConverter
fun listToJson(value: List<YourObject>?): String {
return Gson().toJson(value)
}
@TypeConverter
fun jsonToList(value: String): List<YourObject>? {
val objects = Gson().fromJson(value, List<YourObject>::class.java) as Array<YourObject>
val list = objects.toList()
return list
}
}