我有两个实体。一个是Product,另一个是ProductCategory.Product到ProductCategory的关系是多对一的。我有一个方法来获取所有的ProductCategories.I想要将一个瞬态变量productCount添加到ProductCategory,在那里它有多少产品可用于每个ProductCategory.I有2个解决方案。这两个工作正常。
解决方案1
public List<ProductCategory> getProductCategoryList() {
List<ProductCategory> productCategoryList = this
.getCurrentSession()
.createQuery(
"SELECT pc FROM ProductCategory pc")
.list();
for (ProductCategory category : productCategoryList) {
String categoryId = category.getId().toString();
category.setProductsCount(getCurrentSession()
.createQuery(
"SELECT p FROM Product p WHERE p.productCategory.id=:categoryId")
.setParameter("categoryId", Long.parseLong(categoryId))
.list().size());
}
return productCategoryList;
}
解决方案2
public List<ProductCategory> getProductCategoryList() {
List<ProductCategory> productCategoryList = new ArrayList<ProductCategory>();
List<Object[]> resultList = this.getCurrentSession()
.createQuery("FROM Product p right join p.productCategory")
.list();
for (Object[] array : resultList) {
Product product = null;
ProductCategory productCategory = null;
if (array[1] != null) {
productCategory = (ProductCategory) array[1];
}
if (array[0] != null) {
product = (Product) array[0];
productCategory.setProductsCount(productCategory
.getProductsCount() == null ? 1 : productCategory
.getProductsCount() + 1);
}
if (productCategory != null
&& !productCategoryList.contains(productCategory)) {
productCategoryList.add(productCategory);
}
}
return productCategoryList;
}
这两个解决方案的解决方案是什么?还是其他更好的解决方案? 我对hibernate中的性能比较没有足够的了解。
答案 0 :(得分:1)
如果你总是想要获得这个“财产”,那么我认为你可以在POJO上使用@Formula
并让它更加透明。
ProductCategory.java
上有类似的事情(需要测试):
@Formula("(select count(*) from Product p where p.productCategory.id = id)")
private Long productsCount;
其中id是ProductCategory.java
上的id字段。
修改强>
顺便说一下,现在不要担心性能。只需使代码清晰。一旦运行并运行,您可以对系统进行概要分析,并查看它需要调整的位置。
答案 1 :(得分:1)
这两种解决方案都很复杂,并且从数据库中加载所有类别的产品。如果您准备好这样做,为什么不简单地将关联设为双向,只需致电category.getProducts().size()
来计算您的数量?
如果你真的不想这样做,那么你应该只是执行一个查询来获取类别,然后执行一个额外的查询来从数据库中获取它们的产品数量:
select category.id, count(product.id) from Product product
inner join product.category category
where category.id in :categoryIds
group by category.id
这将返回List<Object[]>
,其中每个Object[]
包含一个类别ID以及相关的产品数。