首页 > 解决方案 > 如何将自定义查询段传递给 RoomDb 中的 @query

问题描述

我正在尝试将 Where 子句传递给 RoomDbD 中的现有查询

@Query("SELECT products_table.id,products_table.name as productName,products_table.image,variations_table.name as variation,variations_table.id as variation_id,variations_table.default_sell_price as selling_price  from products_table INNER JOIN variations_table ON products_table.id = variations_table.product_id LEFT JOIN variations_locations_details_table as VLD ON variations_table.id = VLD.variation_id || :whereClause ")
LiveData<List<VariedProducts>> getProductsWithVariations(String whereClause);

它返回所有数据,而不考虑任何查询,例如

productsDao.getProductsWithVariations("WHERE products_table.id = 4");

任何房间数据库用户协助

标签: androidsqlandroid-room

解决方案


您不会像在旧的 android SQLite 中那样传递 where 子句,而是传递要在 where 子句中使用的参数。

在 Room 中,您编写整个查询,包括带有命名参数的 where 子句,例如 PHP DBO 或 Java JDBC,然后在调用方法时传递参数。

@Query("SELECT * FROM user WHERE username LIKE :username LIMIT 1")
LiveData<User> findByUserName(String username);

因此,对于您的情况,正确的方法是:

@Query("SELECT products_table.id,products_table.name as productName,products_table.image,variations_table.name as variation,variations_table.id as variation_id,variations_table.default_sell_price as selling_price  from products_table INNER JOIN variations_table ON products_table.id = variations_table.product_id LEFT JOIN variations_locations_details_table as VLD ON variations_table.id = VLD.variation_id WHERE products_table.id = :productId")
LiveData<List<VariedProducts>> getProductsWithVariations(Integer productId);

推荐阅读