2012-09-18 47 views
9

我有三個表A B和C.現在我想在HQL執行此SQL查詢:使用左聯接在HQL 3個表

select * from A as a 
left join 
B as b 
on 
a.id = b.id 
left join 
C as c 
on 
b.type=c.type; 

書面相當於HQL需要幫助。我試着用這個的HQL ...

Query q = session.createQuery(
    "FROM A as a 
    LEFT JOIN 
    B as b 
    on 
    a.id=b.id 
    LEFT JOIN 
    C as c 
    on 
    b.type=c.type"); 

此查詢「的」條款引發異常.....

org.hibernate.hql.ast.QuerySyntaxError: unexpected token: LEFT near line 1, column 23 [FROM com.admin.A as a LEFT JOIN B as b where a.Id=b.Id LEFT JOIN C as c where b.type=c.type] at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:74) at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:214) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:127) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:83) at org.hibernate.impl.SessionFactoryImpl.getQuery(SessionFactoryImpl.java:414)

我也試圖與「有」和而不是在那裏...我得到同樣的意外的標記 「上」 或 「與」

例外qith ON .....

org.hibernate.hql.ast.QuerySyntaxError: unexpected token: ON near line 1, column 41 [FROM com.admin.A as a LEFT JOIN B as b on a.Id=b.Id LEFT JOIN C as c onb.type=c.type] at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:74) at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:214) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:127) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:83) at org.hibernate.impl.SessionFactoryImpl.getQuery(SessionFactoryImpl.java:414)

我也試過 「與」 條款s,而不是在那裏......我得到相同的意外的標記或 「與」

例外qith WITH .....

org.hibernate.hql.ast.QuerySyntaxError: unexpected token: ON near line 1, column 41 [FROM com.admin.A as a LEFT JOIN B as b on a.Id=b.Id LEFT JOIN C as c onb.type=c.type] at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:74) at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:214) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:127) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:83) at org.hibernate.impl.SessionFactoryImpl.getQuery(SessionFactoryImpl.java:414)

請幫助。

回答

15

我想你已經在你的配置中定義了所有需要的關聯。如果是這樣,在HQL它應該是這樣的:

from A as a left join a.B as b left join b.C as c 

沒有「ON」的HQL語句,Hibernate並自動根據您的映射和定義的關聯。

請注意a.Bb.C

您可以根據已定義的別名a參考B和C c & c。

+0

你震撼upvoted你 – kakabali

+0

如何將我們的數據存儲到在這種情況下,一個列表? – kakabali

+0

這應該是被接受的答案:) – tusar

7

使用此查詢

from A as a 
left join fetch a.B as b 
left join fetch b.C as c 
+0

你震撼了你 – kakabali