JPA选择ManyToMany上的查询

时间:2015-03-04 17:06:09

标签: sql database java-ee jpa ejb

有人可以帮我解决这个ManyToMany连接上的SELECT查询吗?我想在我的EJB类中选择由user id指定的注册用户。

课程实体代码段

        Public class Course implements Serializable {
    ...
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private long id;

            @ManyToMany
        @JoinTable(name="course_user", joinColumns={@JoinColumn(name="course_id", referencedColumnName="id")},
            inverseJoinColumns={@JoinColumn(name="user_id", referencedColumnName="id")})
        private List<User> enrolledStudents;
    ...

用户实体代码段

public class User implements Serializable {
    private static final long serialVersionUID = 1L;
...

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;

    @ManyToMany(mappedBy="enrolledStudents")
    private List<Course> enrolledCourses;
...

例如,这是我在EJB中的另一个select查询,但它不在ManyToMany上。我想要类似的东西,但无法弄清楚如何......

 public List<Course> findOwndedCourses(long id) {
    TypedQuery<Course> query = entityManager.createQuery("SELECT c FROM Course c WHERE c.owner.id = :ownerId", Course.class);
    query.setParameter("ownerId", id);
    return query.getResultList();
}

谢谢你的帮助!!

1 个答案:

答案 0 :(得分:1)

此查询应该这样做:

select c FROM Course c JOIN c.enrolledStudents u WHERE u.id = :userId

或者这个可能更简单(联接是隐含的):

FROM Course c WHERE c.enrolledStudents.id = :userId