我下面有一个名为Medicine的模型课
@Entity(tableName = "medicine")
data class Medicine(
@Expose(serialize = false, deserialize = false)
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var id: Long,
@SerializedName("productName")
var product_name: String,
@SerializedName("companyName")
var company_name: String
)
}
现在在DAO类中,我想进行如下查询
@Query("SELECT *, COUNT(product_name) as Total FROM medicine GROUP BY product_name")
fun getAllMedicineGroupByProductName(): LiveData<List<Medicine>>
现在我的问题是,如何获得总计?
我不想修改Model,所以如果在Model类中不添加 Total 之类的字段是更好的解决方案,那会很好
我正在使用数据绑定,因此,如何像在那一样获取Total
<TextView
android:id="@+id/tvProductName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{`Product Name : `+medicine.product_name}"
android:textColor="@android:color/black" />
在这里我可以轻松获得product_name,但不知道如何获取总计?预先感谢。
答案 0 :(得分:0)
您只得到一个Medicine对象,它没有Total。您需要获取具有@Embedded Medicine对象和Total的对象(POJO)
喜欢
data class MedicineWithTotal(
@Embedded val medicine: Medicine,
val Total: Int
)
使用方式类似于:-
database.medicineDao().insertMedicine(Medicine(0,"tableta","ZZZ"))
database.medicineDao().insertMedicine(Medicine(0,"tabletb","ZZZ"))
database.medicineDao().insertMedicine(Medicine(0,"tabletc","ZZZ"))
database.medicineDao().insertMedicine(Medicine(0,"tabletc","XXX"))
database.medicineDao().insertMedicine(Medicine(0,"tabletc","YYY"))
val medicinewithcount = database.medicineDao().getAllMedicineGroupByProductName()
for (mwt: MedicineWithTotal in medicinewithcount) {
Log.d("COUNT","Product = " + mwt.medicine.product_name + " Count = " + mwt.Total)
}
for (mwt: MedicineWithTotal in medicinewithcount) {
Log.d("MEDICINEWITHCOUNT","Product = " + mwt.medicine.product_name + " Count = " + mwt.Total)
}
确实
D / COUNT:产品=平板电脑计数= 1
D / COUNT:产品= tabletb计数= 1
D / COUNT:产品= Tabletc计数= 3
(对LiveData的处理不那么容易)