jpa One to One mapping One To One relation between employee and desk


Consider a one to one bidirectional relationship between employee and desk.

public class Employee {

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

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

    // getters and setters    

public class Desk {

    @TableGenerator(table = "id_gen", name = "desk_gen", pkColumnName = "gen_name", valueColumnName = "gen_value", allocationSize = 1)
    @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    

Test Code

/* Create EntityManagerFactory */
    EntityManagerFactory emf = Persistence

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

    Employee employee;

    employee = new Employee();

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


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

Database diagram is depicted as below. enter image description here

  • The @JoinColumn annotation goes on mapping of the entity that is mapped to the table containing the join colulmn.The owner of relationship. In our case, Employee table has the join column so @JoinColumn is on Desk field of Employee entity.
  • The mappedBy element should be specified in the @OneToOne association in the entity that reverse side of relationship. i.e. The entity which does not provide join column on database aspect. In our case, Desk is the inverse entity.

Complete example can be found here