Search code examples
jpajpql

JPA-JPQL query to fetch child entity field with all parent entity fields


I have below requirement to implement in JPQL but couldn't able to do it. Please help me here.

I have parent entity Task and two child entities MoveTask and PickTask.

These looks like below.

@Entity
class Task{
    String taskId;
    String taskName;
    String taskDesc;
}

class MoveTask extends Task{
    String moveType;
}


class PickTask extends Task{
    String taskType;
}

The existing JPQL Query:

String Query="SELECT task.taskId,task.taskName,task.taskDesc FROM TASK";

As per my new requirement I need to get the taskType field which is there in PickTask.

If I change the query as below it is not fetching the moveTaks records from db.

String newQuery="SELECT task.taskId,task.taskName,task.taskDesc,task.taskType FROM PickTask"

I want to fetch all records from db but the above one fetching PickTask Type only.

Appreciate your help here.


Solution

  • I managed to fix the issue by using LEFT JOIN in JPQL.

    The query as given below.

    SELECT task.taskId,task.taskName,task.taskDesc,pickTask.taskType FROM Task task LEFT JOIN PickTask pickTask on (task.taskId=pickTask.taskId);**
    

    Thank you @fangdi your idea helps me to think differently and fix this.