一、one to one,從表主鍵引用主表主鍵
主表實體:
- @Entity
- @Table(name="EMPLOYEE")
- public class Employee {
-
- @Id
- @GeneratedValue
- @Column(name="employee_id")
- private Long employeeId;
-
- @Column(name="name")
- private String name;
-
- @OneToOne(mappedBy="employee", cascade=CascadeType.ALL)
- private EmployeeDetail employeeDetail;
-
- public Employee() {
-
- }
-
- // Getter and Setter methods
- }
從表實體:
- @Entity
- @Table(name="EMPLOYEEDETAIL")
- public class EmployeeDetail {
-
- @Id
- @Column(name="employee_id", unique=true, nullable=false)
- @GeneratedValue(generator="gen")
- @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="employee"))
- private Long employeeId;
-
- @Column(name="street")
- private String street;
-
- @OneToOne
- @PrimaryKeyJoinColumn
- private Employee employee;
-
- public EmployeeDetail() {
-
- }
-
- // Getter and Setter methods
- }
注意:設定mappedBy的那一方不進行主表到從表關系的維護,即對employee的更改,不會影響到employeedetail。