2014-06-18 67 views
0

這個HQL查詢一直在把我拉上一堵牆,我希望有人能幫助我。這裏是我的數據模型:HQL連接查詢加入多對一關係的單行

public class Record { 
    private int id; 
    private String name; 
    private Set<RecordFieldData> recordFieldData; 
} 

public class RecordFieldData { 
    private int id; 
    private String data; 
    private Record record; 
    private RecordTypeField type; 
} 

public class RecordTypeField { 
    private int id; 
    private String dataType; 
} 

下面是一些數據:

Record 
------------------------------------------------- 
| id  | name        | 
------------------------------------------------- 
| 1  | Abc         | 
| 2  | 123         | 
| 3  | Xyz         | 
------------------------------------------------- 

RecordFieldData 
------------------------------------------------- 
| id  | record_id | data   | type_id | 
------------------------------------------------- 
| 1  | 1   | Blue   | 1  | 
| 2  | 1   | Round  | 2  | 
| 3  | 2   | Red   | 1  | 
| 4  | 2   | Square  | 2  | 
| 5  | 3   | White  | 1  | 
| 6  | 3   | Oval   | 2  | 
------------------------------------------------- 

RecordTypeField 
------------------------------------------------- 
| id  | dataType       | 
------------------------------------------------- 
| 1  | Color        | 
| 2  | Shape        | 
------------------------------------------------- 

我需要的是由RecordField.data排序的某些類型的記錄列表。例如,對RecordField.data中的記錄進行排序,但僅對'color'類型的RecordFieldData進行排序。 RecordFieldData.data不必在查詢中返回,我可以在以後獲取,但我需要在查詢記錄中進行排序(否則分頁將不起作用)。記住Record的某個類型的RecordFieldData可能會丟失,但我仍然希望列表中的記錄。

我嘗試這樣的查詢,但我得到重複的記錄,因爲所加入我不想RecordFieldData行:

SELECT r FROM Record r 
LEFT JOIN r.recordFieldData AS field 
LEFT JOIN field.type AS typeField WITH typeField.dataType = 'color' 
ORDER BY LOWER(field.data) 

有什麼建議?

回答

1

編輯

只看見自己的需要返回所有記錄的要求。所以用JOIN替換LEFT JOIN,因爲我最初建議不起作用。

嘗試使用DISTINCT代替

SELECT DISTINCT r FROM Record r 
LEFT JOIN r.recordFieldData AS field 
LEFT JOIN field.type AS typeField WITH typeField.dataType = 'color' 
ORDER BY LOWER(field.data) 

EDIT 2

我認爲使用LEFT JOIN FETCH需求,雖然我不知道爲什麼它給你一個錯誤的最後一次。也許這樣的事情

SELECT DISTINCT r FROM Record r 
LEFT JOIN FETCH r.recordFieldData AS field 
LEFT JOIN FETCH field.type AS typeField WITH typeField.dataType = 'color' 
ORDER BY LOWER(field.data) 
+0

謝謝,這對這個問題的工作......我實際上有一個更復雜的查詢建立在此數據模型上,我應該創建一個新的問題? – Osman

+0

@Osman肯定,我會看看 – FuzzyTree

+0

http://stackoverflow.com/questions/24293418/hql-double-join-query-with-one-to-many-relationship 非常感謝! – Osman