JPA一对一双向映射不起作用

时间:2017-07-06 18:23:44

标签: hibernate jpa

我有以下员工和部门课程,当我从员工到部门班级进行单向一对一映射工作正常时,我会获得员工详细信息以及部门详细信息

@Entity
@Table(name="EMPLOYEES")
public class Employees implements Serializable {

@Id
@Column(name="EMPLOYEE_ID")
private Integer employee_id;

@Column(name="FIRST_NAME")
private String first_name;

@Column(name="LAST_NAME")
private String last_name;

@Column(name="EMAIL")
private String email;

@Column(name="PHONE_NUMBER")
private String phone_number;

@Column(name="HIRE_DATE")
private Date hire_date;

@Column(name="JOB_ID")
private String job_id;

@Column(name="SALARY")
private double salary;


@Column(name="COMMISSION_PCT")
private String commission_pct;

@Column(name="MANAGER_ID")
private String manager_id;


@OneToOne
@JoinColumn(name="department_id")
private Departments departments;

}

对于上面的映射我正确地得到了结果,但当我在Departments类中放置双向映射时,如下所示,在访问员工时出错

@Entity
@Table(name="DEPARTMENTS")
public class Departments {
@Id
@Column(name="DEPARTMENT_ID")
private Integer department_id;

@Column(name="DEPARTMENT_NAME")
 private String department_name;

@Column(name="MANAGER_ID")
 private String manager_id;

@Column(name="LOCATION_ID")
 private String location_id;

@OneToOne(mappedBy="departments")
private Employees employees;

public Employees getEmployees() {
    return employees;
}

}

    org.hibernate.event.internal.DefaultLoadEventListener doOnLoad
INFO: HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 90, for class: com.example.demo.entity.Employees

以下是访问员工的代码

@RequestMapping(value="/getEmployees",method=RequestMethod.GET)
public ResponseEntity<List<Employees>> getEmployees(){
    System.out.println("Employees are ");
    List<Employees> employees =(List<Employees>) employeeRepo.findOne(new Integer(100));
    //System.out.println(employees.getDepartments());
    return new ResponseEntity(employees,HttpStatus.OK);

}

下面是用于检索部门的代码,这些部门使用双向映射多次给出相同的结果(递归结果)

访问部门的代码

@RequestMapping(value="/getDepartments",method=RequestMethod.GET)
    public ResponseEntity<Departments> getDepartments(){
        System.out.println("Departments are ");
        Departments dept = (Departments) departmentRepo.findOne(new Integer(10));

        return new ResponseEntity(dept,HttpStatus.OK);

    }

请有人帮帮我吗?

1 个答案:

答案 0 :(得分:1)

您没有使用正确的映射。虽然每个员工可能只有一个部门,但每个部门可能只有一个以上的员工。因此,您在查询中看到的错误。它只期待一名员工,但却有多名员工。