java - Which solution has better performance when counting with hibernate -
i have 2 entities.one product , other productcategory.product productcategory relationship many one.i have method productcategories.i want add transient variable productcount productcategory shous how many products available each productcategory.i have 2 solutions these.both working fine.
solution 1
public list<productcategory> getproductcategorylist() { list<productcategory> productcategorylist = .getcurrentsession() .createquery( "select pc productcategory pc") .list(); (productcategory category : productcategorylist) { string categoryid = category.getid().tostring(); category.setproductscount(getcurrentsession() .createquery( "select p product p p.productcategory.id=:categoryid") .setparameter("categoryid", long.parselong(categoryid)) .list().size()); } return productcategorylist; }
solution 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(); (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; }
what better solution these two? or other better solution ? don't have sound knowledge on comparison of performances in hibernate.
both of these solutions complex, , load products of categories database. if you're ready that, why don't make association bidirectional, , call category.getproducts().size()
count?
if don't want that, should execute query categories, , execute single additional query product count database:
select category.id, count(product.id) product product inner join product.category category category.id in :categoryids group category.id
this return list<object[]>
, each object[]
contains 1 of category ids, , associated count of products.
Comments
Post a Comment