Is there a way to join two tables in Spring JPA without using association class.
I have two MySQL DB tables : employees(id,.....,department_id) departments(id,.....) And I'm searching for a way to join these tables using only my employee and department classes.
Currently, I managed to join two tables but with the third association class. My current implementation is:
Employee class:
@Entity(name = "Employee")
@Table(name = "employees")
@JsonInclude(Include.NON_NULL)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
@Column(name = "employee_id")
private Long employeeId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "phone_number")
private String phoneNumber;
@Column(name = "hire_date")
private Double hireDate;
@Column(name = "job_id")
private Long jobId;
@Column(name = "salary")
private Double salary;
@Column(name = "commission_pct")
private Double commissionPct;
@Column(name = "employees")
private Long employees;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id", insertable = false, updatable = false)
@Fetch(FetchMode.JOIN)
private Department department;
}
Department class:
@Entity(name = "Department")
@Table(name = "departments")
@JsonInclude(Include.NON_NULL)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "department_name")
private String departmentName;
@Column(name = "department_id")
private long departmentId;
@Column(name = "manager_id")
private Double managerId;
@Column(name = "location_id")
private Double locationId;
}
Association class:
public class DeptEmpDto {
private long departmentId;
private String departmentName;
private Double managerId;
private Double locationId;
private long employeeId;
private String firstName;
private String lastName;
private String phoneNumber;
private Double hireDate;
private Long jobId;
private Double salary;
private Double commissionPct;
}
Repository:
public interface IEmployeeRepository extends JpaRepository<Employee, Long> {
@Query("SELECT new com.concretepage.entity.DeptEmpDto(d.departmentId,d.departmentName,d.managerId,d.locationId,e.employeeId,e.firstName,e.lastName,e.phoneNumber,e.hireDate,e.jobId,e.salary,e.commissionPct FROM Employee e INNER JOIN Department d ON d.id = e.jobId")
List<DeptEmpDto> fetchEmpDeptDataInnerJoin();