Search code examples
javadatabasejpamany-to-many

Query for getting data not attached to a particular variable - JPA


I have a table of Employee's and a Meeting variable (also I have a table for Meeting). The relationship beetween Meeting and Employee is many-to-many. Is it possible to write a JPA Query which gets all the Employees from the database which are attached to the Meeting variable. If so what is the query ? The other option is to get all Employees and see which ones are not in the Meeting variable, but maybe is slow. Any ideas what should I do ?


Solution

  • For example this is your Employee entity:

    @Entity
    public class Employee  {
    
        @ManyToMany(mappedBy="employee")
        private List<Meeting> meetings;
        ...
    }
    

    Query: Get all the Employees from the database which are attached to the Meeting variable

    SELECT e FROM Employee e WHERE :meeting MEMBER OF e.meetings
    

    Query: Get all Employees and see which ones are not in the Meeting variable

    SELECT e FROM Employee e WHERE :meeting NOT MEMBER OF e.meetings
    

    Sample code:

    String query = "SELECT e FROM Employee e WHERE :meeting MEMBER OF e.meetings";
    
    Meeting meeting = new Meeting();
    meeting.setId(1);
    
    TypedQuery<Employee> query = em.createQuery(query, Employee.class);
    List<Employee> employeesInMeeting = query.setParameter("meeting", meeting).getResultList();  
    // this will select all employees that has a meeting with id=1 in their list