2016-05-12 55 views

回答

0

你可以寫一個DetachedCriteria讓你的score_id, max(version_no)對的列表和與您的外部Criteria做一個多屬性IN()

DetachedCriteria subQuery = DetachedCriteria.forClass(ScoreVersion.class); 
subQuery.setProjection(
     Projections.projectionList() 
     .add(Projections.groupProperty("scoreId")) 
     .add(Projections.max("versionNumber") 
    ) 
); 

Criteria criteria = this.getSession().createCriteria(ScoreVersion.class); 
criteria.add(
    Subqueries.propertiesIn(new String[] {"scoreId", "versionNumber"}, subQuery) 
); 

蓋下產生的SQL應該是這個樣子:

select * from [ScoreVersion] where ([score_id], [Version_No]) in (
    select [score_id], max([Version_No]) from [ScoreVersion] group by [score_id] 
); 

此前休眠4:

你不得不編寫查詢在HQL:

Query query = session.createQuery(String sql); 

其中您的查詢是:

select sv from ScoreVersion sv 
where (sv.scoreId, sv.versionNumber) in (
    select sub.scoreId, max(sub.versionNumber) 
    from ScoreVersion sub 
    group by sub.scoreId 
) 
+0

Dean Clark,我使用hibernate 3.jar,Subqueries.propertiesIn方法沒有在這個版本中獲得。 –

+0

它被添加了Hibernate 4(https://hibernate.atlassian.net/browse/HHH-6766)。如果你可以升級,很好......否則你需要在HQL中編寫查詢 –