如何使用hibernate中的join从两个表中获取列

时间:2014-10-24 15:02:45

标签: java hibernate

我有两个表Employee和Department如下:

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;


@Entity
@Table(name="EMPLOYEE")
public class Employee {

@Id
@GeneratedValue
@Column(name="employee_id")
private Long employeeId;

@Column(name="firstname")
private String firstname;

@Column(name="lastname")
private String lastname;

@Column(name="birth_date")
private Date birthDate;

@Column(name="cell_phone")
private String cellphone;

@ManyToOne
@JoinColumn(name="department_id")
private Department department;

public Employee() {

}

public Employee(String firstname, String lastname, String phone) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.birthDate = new Date(System.currentTimeMillis());
    this.cellphone = phone;
}

// Getter and Setter methods
}

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

 @Entity
@Table(name="DEPARTMENT")
  public class Department {

@Id
@GeneratedValue
@Column(name="DEPARTMENT_ID")
private Long departmentId;

@Column(name="DEPT_NAME")
private String departmentName;

@OneToMany(mappedBy="department")
private Set<Employee> employees;

// Getter and Setter methods
}

表格看起来像这样:

enter image description here

现在我想让员工的姓氏为Mayers,部门名称为sales。

所以我想做连接,下面是我写的HQL查询:

String hql="    select e.employeeId, e.firstName from Employee E join Department D on E.department.departmentId = D.departmentId where e.lastName= :param1 and d.departmentName= :param2"

        query.setParameterList("parm1", "Mayers");
        query.setParameterList("parm2", "sales"));

我得到一个例外,说明加入的路径。 我尝试给出完全限定的名称com.myexample.Department然后我得到了没有左侧的点节点。你们能指点我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

试试这个

select e.employeeId, e.firstName from Employee e join e.department d where e.lastName= :param1 and d.departmentName= :param2