2017-02-23 110 views
0

我使用Spring Data JPA作爲我的存儲庫層和Spring安全性作爲我的安全層。在我的項目中,Department和Employee之間具有以下單向一對多關係。以下是這兩個實體的片段。查找由集合中的相關實體過濾的實體

@Entity 
public class Department { 
    ... 

    @OneToMany 
    @JoinColumn(name="department") 
    private Set<Employee> members;   

    ... 
} 

@Entity 
public class Employee { 
    ... 

    private String username; 

    ... 
} 

的關係必須是單向的,由於有一定的限制,我的用例之一是找到一個登錄的用戶的部門。

我的問題是,如何使用spring數據查詢方法或jpql基於當前登錄的用戶(即登錄的當前用戶必須通過用戶名字段匹配1個Employee對象)過濾出一個Department實體?

回答

0

我想通了,我怎麼能要求通過Spring數據JPA @Query方法來實現,而不需要與Employee對象只是用戶名進行比較。

@Query("select dept from Department dept inner join dept.members member where member.username = ?1") 
Department findDeptByQuery(String username) 
1

使用JPQL您可以使用MEMBER OF集合謂詞。

//Fetch <YOUR EMPLOYEE ENTITY TO MATCH> or 
//Create an new EMPLOYEE object with its primary key prepopulated if you already know it. 
Query query = SELECT d FROM Department d WHERE :employee MEMBER OF d.members 
query.setParameter("employee", <YOUR EMPLOYEE ENTITY TO MATCH>); 
query.list(); 
+0

您的回答很接近。不過,我正在尋找一種不需要與對象進行比較的方法。 – Qcumber