我有一个 raw sql query ,我需要在hibernate criteria 中编写 .
raw sql query 我有:
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
它的作用是,
-
按
ORDER BY Sort1 DESC, Sort2 DESC, Sort3 DESC
排序t1表结果 -
为每个年龄组选择一行
-
按
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
我有一张 table 如下: Table t1
| 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
---------------------------------------------------------------------------
从上面的sql查询返回的结果如下:
| 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
看起来像 DetachedCriteria 是前进的方向,看到一些解决方案使用DetachedCriteria的结果提供给 where clause ,但 not directly after FROM .
所以我使用DetachedCriteria创建子查询,但不知道在哪里完成Criteria .
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"))
我非常感谢您对如何去做的见解 . 先感谢您 :)