Hibernate查询与额外列的多对多关系

时间:2016-08-22 18:16:50

标签: java hibernate

我是Hibernate的新手,我正在试图找出如何查询多个到多个关系映射为实体,因为需要额外的列。

特别是,按照我在codejava.net(http://www.codejava.net/frameworks/hibernate/hibernate-many-to-many-association-with-extra-columns-in-join-table-example)找到的示例,我映射了这样的关系:

Student.java

@Entity
public class Student implements Serializable {

    @Id
    @Column
    private String email;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String surname;

    // Constructor, getters, setters, hashcode, equals
 }

Course.java

@Entity
@Table( 
    uniqueConstraints = @UniqueConstraint(
                            columnNames {"name","year"})
)
public class Course implements Serializable {

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

    @Column
    private String name;

    @Column
    private String year;

    @OneToMany(mappedBy = "course")
    private Set<Student_Course> students = new LinkedHashSet<>();

    // Constructor, getters, setters, hashcode, equals
}

Student_Course.java

@Entity
public class Student_Course implements Serializable {

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

    @ManyToOne
    @JoinColumn(name = "student_email")
    private Student student;

    @ManyToOne
    @JoinColumn(name = "course_id")
    private Course course;

    @Column(nullable = false,
            columnDefinition = "int default 0")
    private int score;

    // Constructor, getters, setters, hashcode, equals
}

现在我想要实现的是通过hql查询找出在给定课程中注册的学生的姓名和姓氏(我知道课程的名称和年份)。 我知道这可能很容易,但我无法在HQL中生成一个有效的查询。

提前谢谢。

2 个答案:

答案 0 :(得分:1)

我相信这个查询可以做你想做的事情:

SELECT sc.student.name, sc.student.surname
FROM Course c JOIN c.students sc 
WHERE c.name = :name AND c.year = :year

答案 1 :(得分:0)

Select name, surname from Student where email in 
(Select student.email from Student_Course 
where Student_course.course.name=:courseName and Student_course.course.year= :year)

然后设置courseName和year

更新

Select student.name,student.surname from Student_Course 
where Student_course.course.name=:courseName and Student_course.course.year= :year
相关问题