Reputation: 1
Hello, I am trying to get max, avg, sum of "productCount". I write this code. I can not find what to do to fix this.
Database query : select sum(product.PRODUCT_COUNT), avg(product.PRODUCT_COUNT), max(product.PRODUCT_COUNT) from product where product.PRODUCT_COUNT>5;
Java Code :
HibernateTemplate template = getHibernateTemplate();
DetachedCriteria criteria = DetachedCriteria.forClass(Product.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.max("productCount"));
projectionList.add(Projections.avg("productCount"));
projectionList.add(Projections.avg("productCount"));
criteria.add(Restrictions.gt("productCount", 4));
criteria.setProjection(projectionList);
List<?> list = template.findByCriteria(criteria);
System.out.println(list.get(0));
System.out.println(list.get(1));
System.out.println(list.get(2));
Hibernate mapping :
<hibernate-mapping>
<class name="com.i2gether.hibernate.model.Product" table="PRODUCT">
<id name="id" column="ID">
<generator class="native"/>
</id>
<property name="productID" type="string" column="PRODUCT_ID"/>
<property name="productName" type="string" column="PRODUCT_NAME"/>
<property name="productDescription" type="string" column="PRODUCT_DESCRIPTION"/>
<property name="productCount" type="int" column="PRODUCT_COUNT"/>
<property name="buyingDate" type="timestamp" column="BUYING_DATE"/>
</class></hibernate-mapping>
But i did not get result what i wanted. Please help me.
Upvotes: 0
Views: 430
Reputation: 844
I think yo have missed few things as per your Db query as i have already mentioned in comments as well. instead of using 2 times avg replace with sum and change your greater condition from 4 to 5. i have mentioned below for your reference
HibernateTemplate template = getHibernateTemplate();
DetachedCriteria criteria = DetachedCriteria.forClass(Product.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.max("productCount"));
projectionList.add(Projections.avg("productCount"));
projectionList.add(Projections.sum("productCount"));
criteria.add(Restrictions.gt("productCount", 5));
criteria.setProjection(projectionList);
List<?> list = template.findByCriteria(criteria);
System.out.println(list.get(0));
System.out.println(list.get(1));
System.out.println(list.get(2));
Upvotes: 0