使用HQL从具有一对多关系的连接表中进行选择

时间:2017-02-28 08:28:06

标签: java oracle hibernate

我有两个班级,之间我有一对多的关系。这些课程是:

@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命令获取每个部门的所有员工字段(传递参数部门名称)感兴趣

3 个答案:

答案 0 :(得分: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)
}

希望这会有所帮助。快乐的编码!

答案 1 :(得分:0)

您是否尝试从Employee类中选择子句为department。 depName =:passingParam

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

答案 2 :(得分: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)