員工與服務檯之間的一對一關係

考慮員工和服務檯之間的一對一雙向關係。

Employee.java

@Entity
public class Employee {

    @TableGenerator(name = "employee_gen", table = "id_gen", pkColumnName = "gen_name", valueColumnName = "gen_val", allocationSize = 100)
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "employee_gen")
    private int idemployee;
    private String firstname;
    private String lastname;
    private String email;

    @OneToOne
    @JoinColumn(name = "iddesk")
    private Desk desk;

    // getters and setters    
}

Desk.java

@Entity
public class Desk {

    @TableGenerator(table = "id_gen", name = "desk_gen", pkColumnName = "gen_name", valueColumnName = "gen_value", allocationSize = 1)
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "desk_gen")
    private int iddesk;
    private int number;
    private String location;
    @OneToOne(mappedBy = "desk")
    private Employee employee;

    // getters and setters    
}

測試程式碼

/* Create EntityManagerFactory */
    EntityManagerFactory emf = Persistence
            .createEntityManagerFactory("JPAExamples");

    /* Create EntityManager */
    EntityManager em = emf.createEntityManager();

    Employee employee;

    employee = new Employee();
    employee.setFirstname("pranil");
    employee.setLastname("gilda");
    employee.setEmail("sdfsdf");

    Desk desk = em.find(Desk.class, 1); // retrieves desk from database
    employee.setDesk(desk);

    em.persist(employee);

    desk = em.find(Desk.class, 1); // retrieves desk from database
    desk.setEmployee(employee);
    System.out.println(desk.getEmployee());

資料庫圖如下所示。 StackOverflow 文件

  • 所述 @JoinColumn 註釋的推移被對映到包含關係的加入 colulmn.The 所有者表中的實體的對映。在我們的示例中,Employee 表具有連線列,因此 @JoinColumn 位於 Employee 實體的 Desk 欄位上。
  • 所述的 mappedBy 元件應在指定 @OneToOne 在於反轉關係的一側的實體的關聯。即在資料庫方面不提供連線列的實體。在我們的例子中,Desk 是反向實體。

完整的例子可以在這裡找到