2014-02-11 90 views
0

我想通過使用下面的JPQL對Faculty實體進行排序,但我正在檢索太多具有相同ID的系。通過關聯字段(OneToMany)排序

@NamedQuery(
     name = "Faculty.findFacultySortedByPreferredTime", 
     query = "SELECT f FROM Faculty f JOIN f.preferredTimes p ORDER BY p.day, p.startTime" 
), 

這裏是我的Faculty實體,我的工作

public class Faculty implements Serializable { 

private static final long serialVersionUID = 1L; 
@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
private Long id; 

private String firstName; 
private String middleName; 
private String lastName; 

@OneToMany(cascade = CascadeType.PERSIST) 
@OrderBy(value = "day, startTime") 
private List<PreferredTime> preferredTimes; 

// some codes removed 

我是不是做錯了?

回答

1

大多數情況下,JPA會爲您從數據庫中選擇的每一行返回一個實體,因此,當加入1:M或M:M關係時,會返回多個對象實例。在這種情況下,一個學院有許多首選時間。如果faculty1具有首選的TimeA和preferredTimeC,而faculty2具有首選的TimeB和preferredTimeD,則由於您指定的連接和排序,您將獲得(faculty1,faculty2,faculty1,faculty2)的有序列表。

DISTINCT關鍵字被用於過濾掉非不同的實體/行:

"SELECT DISTINCT f FROM Faculty f JOIN f.preferredTimes p ORDER BY p.day, p.startTime" 
+0

完美地工作!偉大的解釋兩個大拇指! – ltlynx