Room 查询返回的列没有字段

Room The columns returned by the query does not have the fields

我在 'Order' 中保留了一份产品清单。 当我尝试从 Room 获取产品列表时。我收到以下错误。但是我做了一个TypeConvertor。可能是什么错误?

订单

   @Entity(tableName = Order.TABLE_NAME)
@JsonClass(generateAdapter = true)
data class Order(
    @PrimaryKey(autoGenerate = true)
    val id: Long,
    val isSendCheque: Int,
    val phone: String,
    val name: String,
    val comment: String? = "",
    val timeFrom: String,
    val timeTo: String,
    @TypeConverters(Converters::class)
    @ColumnInfo(name = "listProduct")
    var listProduct: List<Product>? = null,
    val publicOrderId: String
) {
    companion object {
        const val TABLE_NAME = "mau_order"
    }
}

产品

@Parcelize
@JsonClass(generateAdapter = true)
data class Product(
        @SerializedName("id")
        @PrimaryKey
        var id: Long = -1,
        @SerializedName("order_id") var orderId: Long = -1,
        @SerializedName("name") var name: String = "name product",
        @SerializedName("packaging") var packaging: String? = "1 кг",
        @SerializedName("path_image") var pathImage: String = "",
        @SerializedName("price") var price: Double = 0.0,
        @SerializedName("price_discount") var priceDiscount: Double = 0.0,
        @SerializedName("product_id") var productId: Int = -1,
        @SerializedName("quantity") var quantity: Double = 0.0,
        @SerializedName("units") var units: String = "ШТ",
        @SerializedName("created_at") var createdAt: String = "",
        @SerializedName("updated_at") var updatedAt: String = "",
        @SerializedName("brgew") var brgew: String = "",
        @SerializedName("gewei") var gewei: String = "кг"
) : Parcelable

OrdersDao

   @Dao
interface OrdersDao {
    /**
     * Inserts [orders] into the [Order.TABLE_NAME] table.
     * Duplicate values are replaced in the table.
     * @param orders Orders
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertOrders(orders: List<Order>)
    /**
     * Inserts [orders] into the [Order.TABLE_NAME] table.
     * Duplicate values are replaced in the table.
     * @param orders Orders
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertOrders(order: Order)

    /**
     * Deletes all the orders from the [Order.TABLE_NAME] table.
     */
    @Query("DELETE FROM ${Order.TABLE_NAME}")
    suspend fun deleteAllOrders()

    /**
     * Fetches the order from the [Order.TABLE_NAME] table whose id is [orderId].
     * @param orderId Unique ID of [Order]
     * @return [Flow] of [Order] from database table.
     */
    @Query("SELECT * FROM ${Order.TABLE_NAME} WHERE ID = :orderId")
    fun getOrderById(orderId: Long): LiveData<Order>

    //ERROR
    @Query("SELECT listProduct FROM ${Order.TABLE_NAME} WHERE ID = :orderId")
    fun getBasketById(orderId: Long): LiveData<Order>

    /**
     * Fetches all the orders from the [Order.TABLE_NAME] table.
     * @return [Flow]
     */
    @Query("SELECT * FROM ${Order.TABLE_NAME}")
    fun getAllOrders(): LiveData<List<Order>>
}

转换器

 @TypeConverter
fun stringToProductList(data: String?): MutableList<Product> {
    if (data == null) {
        return Collections.emptyList()
    }

    val listType = object : TypeToken<MutableList<Product>>() {

    }.type

    return gson.fromJson(data, listType)
}

@TypeConverter
fun ProductListToString(someObjects: MutableList<Product>?): String? {
    if (someObjects == null) {
        return null
    }
    return gson.toJson(someObjects)
}

错误

OrdersDao.java:53: error: The columns returned by the query does not have the fields [id,orderId,name,pathImage,price,priceDiscount,productId,quantity,units,createdAt,updatedAt,brgew,gewei] in com.vepe.navigation.model.entity.Product even though they are annotated as non-null or primitive. Columns returned by the query: [listProduct] public abstract java.util.List<com.vepe.navigation.model.entity.Product> getBasketHistoryFromOrderById(long orderId); Current JDK version 1.8.0_272-b10 has a bug (https://bugs.openjdk.java.net/browse/JDK-8007720) that prevents Room from being incremental. Consider using JDK 11+ or the embedded JDK shipped with Android Studio 3.5+.C:\Users\mind\StudioProjects\Sarah_navigationProject\ProjectAndroid\app\build\tmp\kapt3\stubs\debug\com\vepe\navigation\model\entity\Product.java:8: error: Entity class must be annotated with @Entity

请帮助我!谢谢

更新 我试图把@Entity 注释 我不知道在我的情况下是否有必要 并得到以下错误

error: The columns returned by the query does not have the fields [id,orderId,name,pathImage,price,priceDiscount,productId,quantity,units,createdAt,updatedAt,brgew,gewei] in com.vepe.navigation.model.entity.Product even though they are annotated as non-null or primitive. Columns returned by the query: [listProduct] public abstract kotlinx.coroutines.flow.Flow<java.util.List<com.vepe.navigation.model.entity.Product>> getBasketHistoryFromOrderById(long orderId); Current JDK version 1.8.0_272-b10 has a bug (https://bugs.openjdk.java.net/browse/JDK-8007720) that prevents Room from being incremental. Consider using JDK 11+ or the embedded JDK shipped with Android Studio 3.5+.C:\Users\mind\StudioProjects\Sarah_navigationProject\ProjectAndroid\app\build\tmp\kapt3\stubs\debug\com\vepe\navigation\data\local\dao\OrdersDao.java:53: warning: The query returns some columns [listProduct] which are not used by com.vepe.navigation.model.entity.Product. You can use @ColumnInfo annotation on the fields to specify the mapping. com.vepe.navigation.model.entity.Product has some fields [id, orderId, name, packaging, pathImage, price, priceDiscount, productId, quantity, units, createdAt, updatedAt, brgew, gewei] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: listProduct. Fields in com.vepe.navigation.model.entity.Product: id, orderId, name, packaging, pathImage, price, priceDiscount, productId, quantity, units, createdAt, updatedAt, brgew, gewei.

您需要修复此查询:

@Query("SELECT listProduct FROM ${Order.TABLE_NAME} WHERE ID = :orderId")
    fun getBasketById(orderId: Long): LiveData<Order>

问题是 selected 字段 (listProduct) 和返回类型 (Order) 不匹配。 Room 抱怨它无法理解如何构建只有一个字段的 Order 实例 - listProduct.

最简单的修复方法是 select 创建 Order 实例所需的所有字段:

@Query("SELECT * FROM ${Order.TABLE_NAME} WHERE ID = :orderId")
    fun getBasketById(orderId: Long): LiveData<Order>

很简单,有时有很多查询和数据类我们错过了我们需要的我们写的在代码中.

 //ERROR
    @Query("SELECT listProduct FROM ${Order.TABLE_NAME} WHERE ID = :orderId")
    fun getBasketById(orderId: Long): LiveData<Order>

您在上述查询中 returning Order LiveData,但要求的 listProduct 不正确,要么

  • Make it '*'(获取orders/single订单列表)

    @Query("SELECT * FROM ${Order.TABLE_NAME} WHERE ID = :orderId") fun getBasketById(orderId: Long): LiveData<Order>

  • 或将return值改为LiveData>

    @Query("SELECT listProduct FROM ${Order.TABLE_NAME} WHERE ID = :orderId") fun getBasketById(orderId: Long): LiveData<List<Product>>

这将解决您的问题。

除此之外,我还添加了房间转换,

object RoomConverters {

     @TypeConverter
        @JvmStatic
        fun restoreModelList(listOfString: String): List<RoomModelList> {
            return Gson().fromJson(listOfString, object : TypeToken<List<RoomModelList>>() {
            }.type)
        }
    
        @TypeConverter
        @JvmStatic
        fun saveModelListAsString(listOfString: List<RoomModel>): String {
            return Gson().toJson(listOfString)
        }

}

我想出了这个办法来解决问题

订单服务

@GET("orders/baskethistory/id/{id}")
suspend fun getBasketHistoryById(@Path("id") id: Long): Response<BasketHistory>

对象列表的数据class

data class BasketHistory(
    @SerializedName("basketHistory") val listProduct : MutableList<Product>
)

@Query("SELECT id,listProduct FROM ${Order.TABLE_NAME} WHERE ID = :orderId")
fun getBasketById(orderId: Long): LiveData<BasketHistory>

试一试