我正在尝试加载实体子列表,但我想避免进行 2 次查询。
我正在考虑在 TypeConverter 中进行查询,但我真的不知道这是否是个好主意。
我的实体:
@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 = "")
DAO:
@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(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
}
}
}
它不起作用,因为不能将内部类用作转换器类。
- 这是个好方法吗?
- 当我执行
RoomRegionDao.selectAll
时,如何在区域实体中自动加载“语言环境列表”?
最佳答案
我认为 TypeConverter
仅适用于静态方法。
我是根据 here 中的示例说的和 here
来自关系部分 here :
"Because SQLite is a relational database, you can specify relationships between objects. Even though most ORM libraries allow entity objects to reference each other, Room explicitly forbids this."
所以我想最好是添加 @Ignore
在你的 locales
属性并在 RoomLocaleDao
上创建方法那就是插入 List<Locale>
插入Region后调用。
插入区域的方法可以返回inserted id .
If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List instead. (https://developer.android.com/topic/libraries/architecture/room.html#daos-convenience)
关于android - Android Room 中的实体列表关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44217266/