具有一对多关系的HQL双连接查询

时间:2014-06-18 19:15:20

标签: java sql hibernate 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;
    private User relatedUser;
}

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

以下是一些数据:

Record
-------------------------------------------------
| id      | name                                |
-------------------------------------------------
| 1       | Round Cookie                        |
| 2       | Square Cookie                       |
| 3       | Oval Cookie                         |
-------------------------------------------------

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

RecordTypeField
-------------------------------------------------
| id      | dataType                            |
-------------------------------------------------
| 1       | Creator                             |
| 2       | Shape                               |
| 3       | Owner                               |
-------------------------------------------------

User
-------------------------------------------------
| id      | username                            |
-------------------------------------------------
| 1       | MilaK                               |
| 2       | JenniferA                           |
-------------------------------------------------

我需要的是按创作者用户名排序的记录列表。所以RecordFieldData.relatedUser.username,但仅适用于Creator类型。用户名不必在查询中返回,我可以稍后再说,但我需要在检索记录的查询中进行排序(否则分页不会起作用)。请记住,Record的某些类型的RecordFieldData可能会丢失,但我仍然希望列表中包含该记录。

我尝试了这个查询,但它似乎没有正确排序:

SELECT DISTINCT r FROM Record r 
LEFT JOIN r.recordFieldData AS field 
LEFT JOIN field.relatedUser AS relatedUser 
LEFT JOIN field.type as typeField WITH typeField.dataType = 'Creator' 
ORDER BY LOWER(relatedUser.username)

有什么建议吗?

0 个答案:

没有答案