My goal is to join two persisted entities with relationships @ManyToOne bidirectional and @JoinTable.
Could it be done by one query (HQL, JPQL or SQL)?
@Entity
@Table(name = "position")
public class Position {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "POSITION_ID", updatable = false)
private Long id;
@Column(name = "NAME")
private String name;
@JoinTable(name = "Position_Employee_JT")
@OneToMany(fetch = LAZY, cascade = ALL)
private Set<Employee> employeeSet = new HashSet<();
}
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "EMPLOYEE_ID", updatable = false)
private Long employeeId;
@ManyToOne(fetch = LAZY)
private Position position;
The first attempt:
@Transactional
public void hireEmployee(Long employeeId, Long positionId) {
Employee employee = employeeRepository.getOne(employeeId);
Position position = positionRepository.getOne(positionId);
employee.setPosition(position);
position.addEmployee(employee);
}
It makes:
SELECT = 3
UPDATE = 1
INSERT = 1
The second:
public Employee hireEmployee(Long employeeId, Long positionId) {
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
Position position = em.getReference(Position.class, positionId);
Employee employee = em.getReference(Employee.class, employeeId);
position.addEmployee(employee);
employee.setPosition(position);
em.getTransaction().commit();
}