JPA一对一更新操作

时间:2017-12-30 09:29:36

标签: hibernate

我想通过Parkingspace更新员工,但我没有成功。为什么我不能通过停车位更新员工?

员工类

@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private int id;
private String name;
private String surname;
private int salary;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="park_id", unique=true)
private ParkingSpace parkingSpace;
 ...getter/setter

   }

停车位等级

@Entity
public class ParkingSpace {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private int parkingLot;
private String location;
@OneToOne(mappedBy = "parkingSpace",cascade = CascadeType.ALL, 
        fetch = FetchType.LAZY, optional = false)
private Employee employee;
....getter/setter
}

我想通过Parkingspace更新员工,但我没有成功。数据库没有变化。

...........
entityTransaction.begin();
parkingSpace.setEmployee(employee);
entityTransaction.commit();
.....

1 个答案:

答案 0 :(得分:0)

您必须在提交前指定Session.saveOrUpdate() 此外,您似乎更改了employee关系:

parkingSpace.setEmployee(employee);

请注意,ParkingSpace实体不是Employee与其自身之间关系的所有者,因为员工字段在mappedBy注释中指定了OneToOne

@OneToOne(mappedBy = "parkingSpace",cascade = CascadeType.ALL, 
        fetch = FetchType.LAZY, optional = false)
private Employee employee;

所以调用parkingSpace.setEmployee(employee);将毫无用处 Employee实体是所有者,您应指定:

employee.setParkingSpace(parkingSpace);