我有一个Employee的表和一个Meeting变量(也有一个用于会议的表)。 MeetingEmployee之间的关系是many-to-many。是否可以编写一个JPA查询,该查询从数据库中获取所有附加到Meeting变量的雇员。如果是这样,查询是什么?另一种选择是获取所有雇员,并查看哪些不在会议变量中,但可能很慢。有什么想法我该怎么办?

最佳答案

例如,这是您的Employee实体:

@Entity
public class Employee  {

    @ManyToMany(mappedBy="employee")
    private List<Meeting> meetings;
    ...
}



查询:从数据库中获取附加到的所有雇员
会议变量


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



查询:获取所有员工并查看哪些不在会议中
变量


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


样例代码:

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

09-04 20:50