Bashir
Bashir

Reputation: 2051

JPQL query in joined tables

my question is very simple, though I found multiple solution, but I didn't succeed to implement them correctly, so I'm asking for your help.

in an Entity Class called Prof , I have this :

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer idUser;
    @OneToMany (cascade = PERSIST)
    @JoinTable(name="jnt_Prof_Exam",
                joinColumns = @JoinColumn(name="idUser"), 
                inverseJoinColumns = @JoinColumn(name="idExam"))
        private List<Exam> exams;

now I want to know how to get just the List of Exam for a given idUser

Upvotes: 0

Views: 177

Answers (2)

M.A.Bell
M.A.Bell

Reputation: 416

You can also use the em.find() like this :

EntityManager em;
List<Exam> exams= new ArrayList<>( em.find( Prof.class, givenID ).getExams() );

Upvotes: 0

Pablo Bastidas
Pablo Bastidas

Reputation: 628

You can use this JPQL,

SELECT p.exams FROM Prof p WHERE p.idUser = :id

The call would be something like this:

List<Exam> exams = em.createQuery("...JPQL...")
     .setParameter("id", idUser)
     .getSingleResult();

With this JPQL just going to get the List of exams and not all the objects in class Prof.

Even better, You can use that JPQL with NamedQuery, but with this you can test fast. :)

Upvotes: 2

Related Questions