2012-09-14 41 views
0

我有一個表,如下所示:如何在Hibernate中進行內連接?

ID | loan_profile_id | from_state | to_state |日期

會有特定loan_profile_id多個條目。

我想用Hibernate來獲取特定的時間爲一組loan_profile_id的前最新的條目。這是我怎麼會在SQL中做到這一點:

select lps.* from loan_profile_state_changes lps inner join 
(select max(id) as maxId from loan_profile_state_changes where date < '2012-09-13 00:00:00' and loan_profile_id in (15744,15745,15746,15747,15748,15750,15751) group by loan_profile_id)maxIds 
on maxIds.maxId = lps.id order by lps.id desc; 

我將如何做到這一點在休眠?

回答

0

您可以通過使用Hibernate的HQL

The Hibernate Query Language: Subqueries

+0

... :)似乎完美的重複: [HQL:是否有可能在子查詢上執行INNER JOIN?](http://stackoverflow.com/questions/10624794/hql-is-it-possible-to-perform-an-inner-join-on-a -query) –

+0

是否使用子查詢高效? –

+0

依賴於你的表結構,索引和維度,你可以運行'EXPLAIN'來查看你的查詢是否有效地工作 –

0

從休眠手動做到這一點:

假設你有一個 「貓」 實體引用另一個 「貓」 實體 「伴侶」,

from Cat as cat inner join cat.mate as mate 

它也可以縮寫爲:

from Cat as cat join cat.mate as mate 
0

使用的DetachedCriteria:

DetachedCriteria subQuery = DetachedCriteria.forClass(LoanProfileStateChanges.class); 
subQuery.add(Restrictions.lt("date", new Date()); 
subQuery.add(Restrictions.in("id", Arrays.asList(1,2,3)); 
ProjectionList pl = Projections.projectionList(); 
pl.add(Projections.max("id")).add(Projections.groupProperty("loanProfileId")); 
subQuery.setProjection(pl); 

DetachedCriteria dc = DetachedCriteria.forClass(LoanProfileStateChanges.class); 
dc.add(Subqueries.propertyIn("id", subQuery); 
dc.addOrder(Order.desc("id")); 

(請注意,它不會做一個內部聯接,而是從一個角度執行計劃等價點)

+0

這意味着當查詢數據庫時,它會顯示爲內連接嗎? –

+0

Nop,它會顯示:select * from t1 where id in(your inner join) – Thierry