room error: The columns returned by the query does not have the fields fieldname

room error: The columns returned by the query does not have the fields fieldname

这是一个示例 POJO

public class Product{
  private long id;
  private String name;
  private double price;

 ... constructor for all fields
 ... getters and setters
}

现在,如果我有这样的查询,在我的 productDAO 中

@Query(select id, name from products)
LiveData<List<Product>> getProducts()

我收到如下错误:

The columns returned by the query does not have the fields [price] in ... Product even though they are annotated as non-null or primitive. Columns returned by the query: [id,name]

a) 如果我进入我的产品并设置

@Nullable
private double price;

错误依然存在。

b) 如果我进入我的产品并设置

@Ignore
private double price;

错误消失了,但是如果我有另一个查询,例如

 @Query(select p.id, p.name, p.price, t.someField from products p inner join table t)
    LiveData<List<Product>> getJoinQueryResponse()

因为设置了 @Ignore,价格返回为 0.0。

那么如何解决呢?希望我不需要为房间的每个不同响应制作 POJO...

基本类型默认不为空。将价格设为 Double 这将解决问题,因为届时它可以为空。此外,您可以添加自定义 getter 以避免将价格作为空对象。

public double getPrice(){
    if(this.price == null) return 0.0;
    return this.price;
}

@Ingore 根据您的回答告诉 Room 完全忽略该字段,这不是您想要的。