【问题标题】:Room nested query and subquery房间嵌套查询和子查询
【发布时间】:2019-10-13 18:13:32
【问题描述】:

我在我的 Android 项目中使用 Room 并想编写一个复杂的查询。我搜索了一下,有一些答案女巫说像这样使用 @Embedded:

class TripAndListsAndListItems {
      @Embedded
      var trip: Trip? = null

     @Relation(parentColumn = "creatorId", entityColumn = "remoteId",     entity = User::class)
     var user: List<User>? = null

     @Relation(parentColumn = "remoteId", entityColumn = "tripId", entity = PlanitiList::class)
     var lists: List<ListAndListItems>? = null
}

Here is complete article.

但是我必须在我的代码中弄清楚它以使用循环等来提取我的结果。 我在 @Query 中使用嵌套查询编写了查询,并使用“as”将列与实体字段匹配,如下所示:

这是 ViewModel 类:

class ServiceCard(
    val id: Int,
    val customerInfo: String,
    val time: String,
    val oilFilter: Boolean,
    val airFilter: Boolean,
    val gasFilter: Boolean,
    val oil: Boolean
)

并且 @Doa 有一个像这样的 @Query 方法:

@Dao
interface ServiceCardDao :ICommonDao<ServiceCard>{

   @Query("SELECT s.services_id as id,  " +
        "s.user_mobile_no as customerInfo, " +
        "( " +
        "SELECT count(*) " +
        "FROM service_detail as sd " +
        "WHERE sd.services_id = s.services_id and sd.service_type_id = 1 " +
        ")              as oilFilter, " +
        "( " +
        "SELECT count(*) " +
        "FROM service_detail as sd " +
        "WHERE sd.services_id = s.services_id and sd.service_type_id = 2 " +
        ")         as airFilter, " +
        "( " +
        "SELECT count(*) " +
        "FROM service_detail as sd " +
        "WHERE sd.services_id = s.services_id and sd.service_type_id = 3 " +
        ")         as gasFilter,  " +
        "( " +
        "SELECT count(*) " +
        "FROM service_detail as sd " +
        "WHERE sd.services_id = s.services_id and sd.service_type_id = 4 " +
        ")         as oil, " +
        "s.service_date as time " +
        "FROM services as s ")
   fun selectAllServicesWithDetail(): LiveData<List<model.ServiceCard>>

}

这两者之间有什么优点或缺点吗?

【问题讨论】:

标签: android android-room android-architecture-components


【解决方案1】:

两者都有优势。

Dao 中的编码一个更复杂,另一个在 Entity 中编码更复杂,但 Dao 中的更大复杂度大于 Entities 的复杂度差异。所以简单的道很可能会赢得一些人的青睐。

一个会更有效,因为没有后数据检索循环来获取计数,此外 SQLite 是编译的 C 代码而不是必须解释的 JVM 字节码,因此 SQlite 通常非常有效。然而,效率很可能是一些人为了更简单的编码而愿意放弃的东西,也许是为了人们习惯的东西。

有些人可能会考虑替代方案,例如将 Dao 和 Class 合二为一的DatabaseViews。

【讨论】:

  • 我认为在这种情况下使用 DatabaseViews 是没有用的,因为即使在 WHERE 子句中,我也必须为 SQLite 查询中的每个小更改创建新类。但在 DAO 中,我可以使用绑定参数,这使得 @Query 对于简单的编码目的更加灵活。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多