这个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上的Records进行排序,但仅对类型为&#39; color&#39;的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)
有什么建议吗?
答案 0 :(得分:1)
修改强>
刚看到你需要退回所有记录的要求。因此,如我最初建议的那样,将LEFT JOIN
替换为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)
编辑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)