JPA一对一双向映射不起作用
我有下面的Employees和Departments类,当我做一个从员工到部门类的单向映射时,它的工作正常,我将获得员工详细信息以及部门详细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;
}
对于上述映射我正确地得到结果,但是当我把双向定向映射部门类,如下,得到错误而访问员工
@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
下面是代码访问e mployees
@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名员工,但有多个。
以上是 JPA一对一双向映射不起作用 的全部内容, 来源链接: utcz.com/qa/257725.html