查询具有@ManyToMany 关系的表(Hibernate)

Query for tables with @ManyToMany relation(Hibernate)

我使用 Hibernate.I 重写了我的 SpringMVC 应用程序,尝试使用 SQL 查询(在我开始重写之前使用 group.with 查询为一组学生选择讲座使用 Hibernate)这个查询是:

"SELECT * FROM lectures WHERE id IN (SELECT lecture_id FROM lectures_groups WHERE group_id =?) ORDER BY date_of_lecture"

我有讲座和小组活动:

@Entity
@Table(name = "lectures")
public class Lecture {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "lectures_groups", joinColumns = @JoinColumn(name = "lecture_id"), inverseJoinColumns = @JoinColumn(name = "group_id"))
    private List<Group> groups = new ArrayList<>();
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "teacher_id")
    private Teacher teacher;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "subject_id")
    private Subject subject;
    @Column(name = "date_of_lecture")
    private LocalDateTime date;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "audience")
    private Audience audience;

    public Lecture() {

    }
//getters setters
}

和:

@Entity
@Table(name = "groups")
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "group_name")
    private String name;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cathedra_id", referencedColumnName = "id")
    private Cathedra cathedra;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "lectures_groups", joinColumns = @JoinColumn(name = "group_id"), inverseJoinColumns = @JoinColumn(name = "lecture_id"))
    private List<Lecture> lectures = new ArrayList<>();

    public Group() {

    }
//getters setters
}

我试过类似的东西:

List<Lecture> lectures = session.createQuery("select l from lectures l join l.groups g where g.id=:groupId")
                .setParameter("groupId", group.getId())
                .list();

但我得到异常:org.hibernate.hql.internal.ast.QuerySyntaxException: lectures is not mapped 那我该怎么做呢?

hql 查询中,您需要在查询中提供 entity 的名称,而不是 table 名称。因此,在您的情况下,您应该在查询中将 lectures 替换为 Lecture

List<Lecture> lectures = session.createQuery("select l from Lecture l join l.groups g where g.id=:groupId")
                .setParameter("groupId", group.getId())
                .list();