Hi everyone!
I have a
raw sql query which I need to write in hibernate criteria. The entire codebase I'm working on is all in hibernate criteria, so I'm trying to explore all possibilities with hibernate criteria before moving on to something else eg. using hql or raw query.
If it's not possible to convert the below raw sql query into hibernate, please say so too! It will be much help since my knowledge in hibernate criteria is quite limited. :(
The raw sql query I have is:
Code:
SELECT
*
FROM
(
SELECT
*
FROM
Table t1
ORDER BY Sort1 DESC, Sort2 DESC, Sort3 DESC
)
GROUP BY Age
ORDER BY Sort1 DESC, Sort2 DESC, Sort3 DESC
What it does is,
1. Sort the t1 table(see below) results as per ORDER BY Sort1 DESC, Sort2 DESC, Sort3 DESC
2. Select a single row per Age group
3. Sort the grouped results as per ORDER BY Sort1 DESC, Sort2 DESC, Sort3 DESC
Note) The reason why I need Step 1) before Step 2) is because GROUP BY, be fault, doesn't guarantee ordering and I need to have strict ordering applied to pick the single row per Age group
I have a table as below: Table t1
Code:
| ID | Lastname | Firstname | Age | Created_at | Sort1 | Sort2 | Sort3
---------------------------------------------------------------------------
| 1 | Jolie | Angey | 40 | 2011 | 3 | 2 | 1
| 2 | Pitt | Brad | 41 | 2012 | 2 | 1 | 2
| 3 | Smith | Casey | 40 | 2010 | 3 | 1 | 2
| 4 | Smith | Carey | 40 | 2009 | 3 | 2 | 3
---------------------------------------------------------------------------
The result returned from the above sql query is as follows:
Code:
| ID | Lastname | Firstname | Age | Created_at | Sort1 | Sort2 | Sort3
----------------------------------------------------------------------------
| 4 | Smith | Carey | 40 | 2009 | 3 | 2 | 3
| 2 | Pitt | Brad | 41 | 2012 | 2 | 1 | 2
Based on what I've found so far, it seems like
DetachedCriteria is the way forward, and saw some solutions that use results from
DetachedCriteria feeding to WHERE clause,
but not directly after FROM clause. So I made the subquery using DetachedCriteria, but not sure where to go about completing Criteria.
Code:
DetachedCriteria subQuery = DetachedCriteria.forClass(Some.class, "a")
.addOrder(Order.desc("a.Sort1"))
.addOrder(Order.desc("a.Sort2"))
.addOrder(Order.desc("a.Sort3"));
// stuck from below... :(
Criteria criteria = hibernateSession.createCriteria(??)
.add(Projections.groupProperty("Age"))
If you need any clarification with the explanation above, feel free to let me know!
I would much appreciate your help. Thank you in advance :)