问题
I have to translate the next expression into hibernate criteria api:
select * from games gs
INNER JOIN (select gg.ID, gg.CODE, max(gg.DATE) max_date from games gg
where gg.player_id = 1 group by gg.ID, gg.CODE) ss
on gs.CODE = ss.CODE
and gs.ID = ss.ID
and gs.DATE = ss.max_date
and gs.player_id = 1
How can I do it? I'm able to create inner and outer criteria separetely, but have no idea how to join them:
DetachedCriteria innerCriteria = DetachedCriteria.forClass(Games.class, "gg");
innerCriteria.add(Restrictions.eq("playerId", 1));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("id"));
projectionList.add(Projections.groupProperty("code"));
projectionList.add(Projections.max("date"));
innerCriteria.setProjection(projectionList);
...
Criteria criteria = getSession().createCriteria(Games.class, "gs");
criteria.add(Restrictions.eq("playerId", 1));
criteria.setProjection(Projections.id());
criteria.list();
回答1:
Hibernate does not support subqueries in the from
clause. From the Hibernate 4.3 documentation:
Note that HQL subqueries can occur only in the select or where clauses.
There is a pending feature request for this.
You'll have to rewrite the query to avoid that, or use native queries.
来源:https://stackoverflow.com/questions/35292257/hibernate-criteria-inner-join-to-select