I have a table “exam” and a table “assignee” , with many assignees for an exam with different roles.
I am trying to create a query to fetch all exams with the role for the current user, which could be not assigned to the exam at all. In SQL i would use a left join
SELECT exam.id, exam.title, assignee.role FROM exam JOIN assignee ON exam.id = assignee.exam_id AND user_id = :userId
I am not sure how to do this using hibernate.
My attempt so far:
I have a domain model for Exam like this:
@Table(name = "exam")
@Entity(name = "exam")
public class ExamDto {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToMany(mappedBy = "exam")
private List<AssigneeDto> assignees;
...
}
My thinking was that the list assignees has one record with the assignee for the current user, or is empty if the user is not assigned to the exam.
My query (which is not working):
public interface ExamRepository extends JpaRepository<ExamDto, String> {
@Query("from exam as e left outer join fetch e.assignees as assignee with assignee.username = :username where e.id = 1 ")
ExamDto getByUsername(@Param("username") String username);
}
Which gives the error " with-clause not allowed on fetched associations; use filters" . But i have tried many different variations.
My question is what would be the best way to approach this problem? Do i need to change my domain object or the query? Thanks for any help, it is much appreciated.