简体   繁体   中英

How to set multiple criteria like SUM, MAX, AVG and print it in hibernate template

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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM