简体   繁体   中英

Hibernate group by criteria

i am new to hibernate. I am using hibernate in my project but i am stuck at one point. I have two database tables which is similar to as follows :

First table

Category
id | name
---------
1  | cat1
2  | cat2

Second table

Product
id | categoryid | name
----------------------
1  | 1          | p1
2  | 1          | p2

What i wanted to achieve is to get the resultset containing category and product count in each category.

categoryid  |  productcount
1           |  2
2           |  0

Currently i am able to do it using Hibernate native sql support.

SQL :

SELECT c.id, CASE WHEN x.count IS NULL THEN 0 ELSE x.count END AS productcount
FROM category AS c LEFT OUTER JOIN
(
    SELECT categoryid,count(*) AS count
    FROM product
    GROUP BY categoryid
) AS x
ON x.categoryid = c.id

Please help me out to achieve this using hibernate criteria Thanks

I think you should use stored procedure and what you want as a result declare it as an OUT parameter . This tutorial will help you to write or call stored procedure in hibernate query http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/

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