简体   繁体   中英

coverting sql count aggregate function to hibernate criteria

I have the following sql query which i am trying to covert to a hibernate find:

select column_1, column_2, count(*)
from data_table
group by column_1, column_2
order by column_1, column_2
;

So far this is the code i have:

 DetachedCriteria detachedCriteria = DetachedCriteria.forClass(table.class);
 detachedCriteria.setProjection(Projections.projectionList()
            .add(Projections.groupProperty("column_1"))
            .add(Projections.groupProperty("column_2"))
            .add(Projections.rowCount()))
        .addOrder(Order.asc("column_1"))
        .addOrder(Order.asc("column_2"));

For some reason i am getting the following error: ORA-00979: not a GROUP BY expression

Is this the right way to translate the the sql query using hibernate? if not, what would be a better way

I am also trying to map the returned count column to a transient property in the model object. What would be a good way to implement that?

Thanks

I was able to implement what i was looking for using the code below:

     detachedCriteria.setProjection(Projections.projectionList()
            .add(Projections.groupProperty("column_1"))
            .add(Projections.groupProperty("column_2"))
            .add(Projections.sqlProjection( 
                    "count(*) as counter", 
                    new String[] { "counterproperty" }, 
                    new Type[] { Hibernate.LONG } 
                  )))
              .addOrder(Order.asc("column_1"))
              .addOrder(Order.asc("column_2")); 

               detachedCriteria.setResultTransformer(Transformers.aliasToBean(modelObject.class));

counterProperty is a transient property i added to the model object

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