Entity list relationship in Android room
I'm trying to load the entity sublist, but I want to avoid 2 queries
I'm thinking about querying in TypeConverter, but I really don't know if this is a good idea
My entity:
@Entity
class Region(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var name: String = "",
var locales: List<Locale> = listOf())
@Entity(foreignKeys = arrayOf(ForeignKey(
entity = Region::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("regionId"),
onDelete = CASCADE,
onUpdate = CASCADE
)))
class Locale(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var regionId: Int = 0,
var name: String = "")
DAOs:
@Dao
interface RoomRegionDao{
@Insert
fun insert(region: Region)
@Delete
fun delete(region: Region)
@Query("select * from region")
fun selectAll(): Flowable<List<Region>>
}
@Dao
interface RoomLocaleDao{
@Insert
fun insert(locale: Locale)
@Query("select * from locale where regionId = :arg0")
fun selectAll(regionId: Int): List<Locale>
}
Database:
@Database(entities = arrayOf(Region::class, Locale::class), version = 1)
@TypeConverters(RoomAppDatabase.Converters::class)
abstract class RoomAppDatabase : RoomDatabase() {
abstract fun regionDao(): RoomRegionDao
abstract fun localeDao(): RoomLocaleDao
inner class Converters {
@TypeConverter
fun toLocales(regionId: Int): List<Locale> {
return localeDao().selectAll(regionId)
}
@TypeConverter
fun fromLocales(locales: List<Locale>?): Int {
locales ?: return 0
if (locales.isEmpty()) return 0
return locales.first().regionId
}
}
}
It does not work because inner classes cannot be used as converter classes
>Is this a good way? > When I perform roomregiondao.selectall, how do I automatically load the "regional setting list" in the regional entity?
resolvent:
I think TypeConverter is only applicable to static methods. I say this according to the examples of here and here
From the relationship section here:
So I think it is best to add @Ignore to your locales attribute and create a method on RoomLocaleDao, that is, insert List< Locale> and call it after inserting Region.
The method of inserting region can return inserted ID