Consider a one to one bidirectional relationship between employee and desk.
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
}
Test Code
/* 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());
Database diagram is depicted as below.
Complete example can be found here