【问题标题】:Paging Library: How to merge a result set of 3 Room Entities?分页库:如何合并 3 个房间实体的结果集?
【发布时间】:2019-10-16 07:14:05
【问题描述】:

如果列表项可以直接从 Room Entity as described in this 派生,那么将 Android Paging 库与 Room 一起使用非常简单。但是,如果列表项实际上是由 3 个实体组成的,我们应该如何实现分页呢?

考虑一下,

data class ListItem(val name, val officeAddress, val lastTravelledPlaceName)

@Entity
data class User(@PrimaryKey val id, val name)


@Entity
data class Office(@PrimaryKey val id, val address)

@Entity 
data class Places(@PrimaryKey val id, val name)

一种解决方案是在User 上使用分页,然后在适配器的onBind..() 调用期间查询OfficePlaces,但这似乎不是正确的方法。

【问题讨论】:

  • 你需要扩展 DataSource.Factory 并从那里做必要的事情。
  • 你也可以加入表格。

标签: android android-room android-paging


【解决方案1】:

@Embedded 注解可用于组合类中的实体。

例如,使用问题中的实体,那么 ListItem 类的替代方案可能是:-

class UserOfficePlacesCombined() {

    @Embedded(prefix = "user")
    var user: User? = null
    @Embedded(prefix = "office")
    var office: Office? = null
    @Embedded(prefix = "places")
    var places: Places? = null
}
  • 前缀已用于避免列名歧义,简而言之,所有列都将以相应表的名称作为前缀(请参阅下面的 Dao 查询)

然后您可以使用 Dao 查询提取 UserOfficePlacesCombined,例如:-

@Query("SELECT user.id AS userid, user.name AS username, " +
        "office.id AS officeid, office.address AS officeaddress, " +
        "places.id AS placesid, places.name AS placesname " +
        "FROM User JOIN Office ON User.id = Office.id JOIN Places ON User.id = Places.id")
fun getAllUserOfficePlacesCombined(): UserOfficePlacesCombined
  • 为避免歧义,所有列都已使用 AS 关键字重命名
  • 如果表之间的关系问题没有指示,则查询将根据表的 id 列连接表。
    • 这不太可能在应用程序中使用,但由于缺乏信息和方便起见,已经这样做了。

把这个作为一个例子,做一些假设,然后考虑下面的演示:-

    val userOfficePlacesDoa = db.userOfficePlacesDao()
    val user1 = User(1,"USER1")
    val office1 = Office(1,"Office1")
    val places1 = Places(1,"Place1")

    userOfficePlacesDoa.insertUser(user1)
    userOfficePlacesDoa.insertOffice(office1)
    userOfficePlacesDoa.insertPlaces(places1)
    var uopc: UserOfficePlacesCombined = userOfficePlacesDoa.getAllUserOfficePlacesCombined()
    Log.d("UOPCINFO","User Name is " + uopc.user?.name + " Office Address is" + uopc.office?.address + " Places name is " + uopc.places?.name)

结果是:-

2019-10-16 22:35:16.442 D/UOPCINFO: User Name is USER1 Office Address isOffice1 Places name is Place1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多