2017-02-28 47 views
0

我有兩個類,然後我有一對多的關係。這些類:使用HQL從具有一對多關係的連接表中選擇

@Entity 
@Table(name = "emp300", uniqueConstraints = @UniqueConstraint(columnNames = {"personId", "empName","last_name"})) 
public class Employee implements Serializable{ 

    @SequenceGenerator(name="seq",sequenceName="my_seq") 
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq") 
    @Id 
    private int Pid; 


    private String empName, last_name, position, boss,personId; 
    private String birthDate; 
    private int salary; 


    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "depId", nullable = false) 
    private Department department; 
    //setters and getters 
    } 

和第二個:

@Entity 
@Table(name = "dep300", uniqueConstraints = @UniqueConstraint(columnNames = "depName")) 
public class Department implements Serializable, Comparable<Department> { 

    @SequenceGenerator(name = "seq", sequenceName = "DEPARTMENTS_SEQ") 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq") 
    @Id 
    private int depId; 

    private String depName; 

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "department", cascade=CascadeType.ALL) 
    private Set<Employee> lst = new HashSet<Employee>(0); 
    //setters and getters 
    } 

現在我很感興趣,我怎樣才能白色HQL命令得到全體員工的字段中的每個部門(參數傳遞部門名稱)

回答

0

您是否嘗試從Employee類中選擇with clause是department。 depName =:passingParam

from Employee e where e.department.depName = :passingParam; 
+0

例外。 hibernate.hql.QueryExecutionRequestException:不支持select查詢[來自ge.ufc.hibernate.Emps.Employee e其中e.department.depName =:mname] – Gog1nA

+0

試試這個,它應該在參數和等號之間有一個空格這個: from Employee e where e.department.depName =:mname; 或者您應該在查詢中修復特定的部門名稱,以確保傳遞參數沒有問題。 –

1

首先不要在Department類

public class Department implements Serializable, Comparable<Department> { 
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "department", cascade=CascadeType.ALL) 
    private Set<Employee> lst = new HashSet<Employee>(0); 
} 

以下變化這將幫助你獲取所有員工的工作,當你取的部門。

然後按照如下方法向存儲庫類添加一個方法。我假設你使用某種形式的Spring數據CRUD存儲庫來完成這項工作。 如果沒有根據您的設置做必要的更改。

public interface DepartmentRepository extends JpaRepository<Department, Integer> { 
    @Query("SELECT d from Department d where d.depName = :depName") 
    Department getDepartmentByName(@Param("depNamename") String depName) 
} 

希望這會有所幫助。快樂的編碼!

+0

在你寫這個更改後有異常。同樣的異常:線程「main」中的異常org.hibernate.QueryException:無法解析路徑[d.depName],意外的令牌[d] [從ge.ufc.hibernate.Emps.Department中選擇d,其中d.depName =:depName ] – Gog1nA

+0

@Query(「SELECT d from Department where d.depName =:depName」) 缺少別名「d」,所以它應該是這樣的: @Query(「SELECT d from Department d where d.depName = depName「) –

+0

答案已更新。我很高興你成功了! –

0

讓一切都懶惰,否則當你不需要它們時,你會引入其他查詢的連接。

使用下面的查詢來獲取員工的列表:

SELECT e FROM Employee e WHERE e.department.depName = :departmentName 

或下獲得的部門列表與員工獲取:在線程「主要」組織

SELECT d FROM Department d LEFT JOIN FETCH d.lst WHERE d.depName IN (:departmentNames) 
相關問題