我有两张桌子;
Create table Student (
id int NOT NULL AUTO_INCREMENT,
name varchar(35),
PRIMARY KEY (id)
);
Create table Course (
id int NOT NULL AUTO_INCREMENT,
student_id int,
name varchar(35),
PRIMARY KEY (id),
FOREIGN KEY (student_id)
REFERENCES Student(id)
ON DELETE CASCADE
);
查询:找到学生“约翰”所做的所有课程。
Select C.name
FROM Course C
JOIN Student S
ON S.id=C.student_id
WHERE S.name='John';
如何在JPA查询语言中写这个?如何编写涉及两个与外键相关的表的标准?
public List<Course> findCourseByStudentName(String name) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Course> criteria = cb.createQuery(Course.class);
Root<Course> courseRoot = criteria.from(Course.class);
Join<Course,Student> courseStudent = courseRoot.join(Course_.student);
criteria.select(courseRoot).where(cb.equal(courseStudent.get(Student_.name), "John"));
}
编辑: 这是Student类Student.java
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "name"))
public class Student implements Serializable {
@Id
@GeneratedValue
private Long id;
@NotNull
@Size(min = 1, max = 35)
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy="student")
Set<Course> courses;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setCourses(Set<course> courses) {
this.course = course;
}
public Set<Course> getCourses() {
return courses;
}
}
这是Course课程,Course.java
@Entity
@Table
public class Course implements Serializable {
@Id
@GeneratedValue
private Long id;
@NotNull
@ManyToOne( targetEntity = Student.class )
@JoinColumn( name = "student_id", referencedColumnName = "id")
private Student student;
@NotNull
@Size(min = 1, max = 35)
private String name;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setStudent(String student) {
this.student = student;
}
public String getStudent() {
return student;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return Name;
}
}
答案 0 :(得分:1)
首先,您必须创建两个实体Student
和Course
,并在@ManyToOne
中添加至少Course
个关系。你可以使用JPQL,比如说:
SELECT C.name
FROM Cource C
INNER JOIN Student S
WHERE S.name = :studentName
之后你应该在查询中添加参数并获得List<String>
作为结果
答案 1 :(得分:0)
我的最新版本给出了正确的答案。感谢所有评论。