我在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
}
但是我必须在代码中弄清楚,才能使用循环等提取结果。我在@ 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>>
}
这两个之间有什么优点或缺点?
两者都有优势。
Dao中的编码对于一个实体而言更为复杂,而另一种实体中的编码则更为复杂,但是Dao中的复杂性大于实体的复杂性差异。因此,较简单的Dao可能会赢得某些人的青睐。
一种效率更高,因为没有后期数据检索循环来获取计数,此外,SQLite是编译的C代码,而不是必须解释的JVM字节码,因此SQlite通常非常有效。但是,效率很可能是一些人希望为了更简单的编码而放弃的,或者可能是人们习惯使用的。]
有些人可能会考虑将DatabaseViews之类的替代方案,它将Dao和Class结合为一体。