员工与服务台之间的一对一关系

考虑员工和服务台之间的一对一双向关系。

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 是反向实体。

完整的例子可以在这里找到