Select 如何使用 Room-Database 从多个实体到一个新对象?

How Select From Multiple Entity into a new Object with Room-Database?

我有两个用于 RoomDB 实体的 POJO

@Entity
public class Favorite {...}
@Entity
public class ProductCart {
    Integer productQuantity;
    ...
}

我需要在对象 FavoriteAdapterData

中应用此 select 语句和 return 它
SELECT favorite.*,
       (SELECT CASE count(productQuantity)
               WHEN 0 THEN 0
                      ELSE productQuantity
               END  FROM ProductCart 
        WHERE favorite.id = productId) AS cartQuantity
FROM Favorite favorite

Sqlite statment test

public class FavoriteAdapterData {
    int cartQuantity = 0;
    Favorite favorite;
    ...
}

我试试下面的代码

@Query("SELECT  " +
            "      (    SELECT CASE count(productQuantity) " +
            "           WHEN 0  THEN 0 " +
            "                   ELSE productQuantity  " +
            "           END  " +
            "           FROM ProductCart " +
            "           WHERE productId = favorite.id" +
            "       ) AS cartQuantity" +
            "       ,favorite.* " +
            "FROM Favorite favorite")
    LiveData<List<FavoriteAdapterData>> getFavoriteProducts();

但它没有用,AndroidStudio 通知我这个错误:

Cannot figure out how to read this field from a cursor. 
Favorite favorite; 
             ^

您需要使用 @Embedded 注释将收藏夹 class 嵌入到 FavoriteAdapterData class 中,然后它将确定列和来自收藏夹 class 的 fields/variables

的输出字段

例如:-

public class FavoriteAdapterData {
    int cartQuantity = 0;
    @Embedded
    Favorite favorite;
    ...
}