所以我最近跳进了Room,面对一个关于别名的好奇问题 .
我将简化课程,以便我的例子更清晰 . 假设我有可以包含一些产品的账单 .
我希望在一段时间内(天,小时......)获得一份带有产品的账单清单 .
我需要实体Bill和Product:
实体Bill.java
@Entity
public class Bill{
@PrimaryKey(autoGenerate = true)
int id;
Date date;
}
实体Product.java
@Entity
public class Product{
@PrimaryKey(autoGenerate = true)
int id;
int bill_id;
BigDecimal price;
String name;
}
我有一个POJO代表其产品的账单 .
POJO BillWithProducts.java:
public class BillWithProducts{
@Embedded
public Bill bill;
@Relation(parentColumn = "id", entityColumn = "bill_id")
public List<Product> products;
}
以及查询的Daos:
Dao BillDao.java
@Dao
public abstract class BillDao{
@Query("select * from bill")
public abstract List<Bill> getAllBills();
@Transaction
@Query("select * from bill where date between :startDate and :endDate")
public abstract List<BillWithProducts> getBillsWithProductsByDate(long startDate, long endDate);
}
Dao ProductDao.java:
@Dao
public abstract class ProductDao{
@Query("select * from product")
public abstract List<Product> getAllProducts();
}
到现在为止还挺好 . 但是对于显示首选项,我希望在一行中使用相同名称的产品,并相应地添加其数量和价格 .
为此目的(因为我的Product.java有很多不需要的信息;保持最小化),我创建了Product类的POJO .
POJO ProductMinimal.java:
public class ProductMinimal{
int id;
int bill_id;
BigDecimal price;
String name;
int quantity;
BigDecimal sumPrices;
}
我在BillWithProducts.java中编辑了Relation以获取ProductMinimal的列表 .
已编辑的POJO BillWithProducts.java:
public class BillWithProducts{
@Embedded
Bill bill;
@Relation(parentColumn = "id", entityColumn = "bill_id", entity = Product.class)
public List<ProductMinimal> productsMinimal; //<-- error pointing here
}
并在ProductDao.java中添加了查询 .
Edited dao ProductDao.java:
@Dao
public abstract class ProductDao{
@Query("select * from product")
public abstract List<Product> getAllProducts();
@Query("select id, bill_id, price, name, " +
"count(*) as quantity, sum(price) as sumPrices " +
"from product " +
"group by name")
public abstract List<ProductMinimal> getAllProductsMinimal();
}
最后,我在这里的原因是我得到这个错误指向BillWithProducts.java中的关系...
错误:查询有问题:[SQLITE_ERROR] SQL错误或缺少数据库(没有这样的列:数量)
当然没有这样的专栏,它是别名......
我试过了 :
- 为"count(*) as 'quantity'"等别名添加简单引号
- 删除计数(*);错误发生在sumPrices上
- 在ProductPojo中嵌入产品(因此有"select *"和许多无用的字段)
- 我甚至尝试将产品的现有列用作别名...
你们中的一些人是否已经面临过类似的案件?
编辑:我尝试在数量别名中获取bill_id,如:
@Query("select id, bill_id, price, name, " +
"bill_id as quantity " +
"from product " +
"group by name")
public abstract List<ProductMinimal> getAllProductsMinimal();
仍然没有得到这样的列错误,因此它没有链接到sum或count操作 .
EDIT2:编辑了帖子以包含POJO BillWithProducts.java(它在我的代码中但不在帖子中) .
1 回答
好的,对于测试我尝试在我的产品表中添加数量列,并且代码顺利运行 .
问题是 BillWithProducts.java 中的我的productsMinimal列表包含所有数量字段为0的产品 .
这就像查询没有考虑到分组和计数 .
(我删除了这个数量列,它仅为测试添加)
然后,我尝试使用类似的方案查询我的数据库,但"outside of"此Bill / Product Relation与 getDatabase().productDao().getAllProductsMinimal(bill_id) 调用 .
在这里,我可以得到我的目标!
所以我最终想到的是@Relation注释不允许任何条件 .
最后,我保留了原始的@Relation,得到了我的所有产品,具有名称冗余,并在原始列表的java中创建了我自己的数量和总和的列表 .
因为它赢得了延迟所需数据的显示 .