I have 3 tables for simplicity:
- COMPANY
- EMPLOYEE
- DEVICES
COMPANY has EMPLOYEES and each EMPLOYEE has a number of devices assigned to them. I am interested in a list of companyIds connected to a list of device names they have assigned to employees.
Example Java object:
@Getter
@Setter
@AllArgsConstructor
public class CompanyDevices {
private Long companyId;
private List<String> deviceNames;
}
Or even better a Map would be great: Map<Long, List where Long would be companyId and List would be deviceNames;
Is it even possible to create JPA Query, join all those tables and return list of custom objects or a map using @Query inside JPARepository?
What I have right now is slightly different class:
@Getter
@Setter
@AllArgsConstructor
public class CompanyDevice {
private Long companyId;
private String deviceName;
}
public interface SomeRepository extends JpaRepository<SomeEntity, Long> {
@Query("SELECT " +
"new path.to.CompanyDevice(C.id, D.deviceName) " +
"FROM Company C " +
"JOIN C.employees E " +
"JOIN E.devices D " +
"WHERE C.id IN :companyIds"
)
List<CompanyDevice> findDevicesForCompanies(@Param("companyIds") List<Long> companyIds);
}
Because of this I need to manualy later group by and create a map. So what I would like to do is something like this but I just can't find enough information or it may not even be possible(sorry for pseudo code):
public interface SomeRepository extends JpaRepository<SomeEntity, Long> {
@Query("SELECT " +
"<create map where key is C.id and value is <list of D.deviceName from grouping>>" +
"FROM Company C " +
"JOIN C.employees E " +
"JOIN E.devices D " +
"WHERE C.id IN :companyIds" +
"GROUP BY C.id"
)
Map<Long, List<String>> findDevicesForCompanies(@Param("companyIds") List<Long> companyIds);
}