I have an entity relationship such that:
STUDENT many-to-one STUDENT_COURSE one-to-many COURSE
Basically, there's a many-to-many
relationship between students and their courses. That relationship is represented by the STUDENT_COURSE
table.
Assume I have entities set up for STUDENT
, STUDENT_COURSE
, and COURSE
such that:
@Entity
@Table(name = "STUDENT")
public course Student {
@Id
@Column(name = "ID", nullable = false)
private Long id;
@OneToMany(mappedBy = "student")
private Set<StudentCourse> studentCoursees;
// ... other fields and getters and setters
}
@Entity
@Table(name = "COURSE")
public course Course {
@Id
@Column(name = "ID", nullable = false)
private Long id;
@OneToMany(mappedBy = "course")
private Set<StudentCourse> studentCourses;
// ... other fields and getters and setters
}
@Entity
@Table(name = "STUDENT_COURSE")
public course StudentCourse {
@Id
@Column(name = "ID", nullable = false)
private Long id;
@ManyToOne
@JoinColumn(name = "STUDENT_ID", referencedColumnName = "ID")
@NotNull
private Student student;
@ManyToOne
@JoinColumn(name = "COURSE_ID", referencedColumnName = "ID")
@NotNull
private Course course;
// ... other fields and getters and setters
}
Then I have a complicated criteria query I'm creating for search purposes that wants all of the students for a particular course. I have the courseId
that I want to add to the restriction. In SQL, I'd do something like this:
select *
from STUDENT, STUDENT_COURSE
where STUDENT.ID = STUDENT_COURSE.STUDENT_ID
and STUDENT_COURSE.COURSE_ID = <courseId>
Notice that I'm only joining STUDENT
and STUDENT_COURSE
. With criteria and the entities set up as described above, it seems like I'm forced to join STUDENT
, STUDENT_COURSE
, and COURSE
because I don't have a courseId field on STUDENT_COURSE
:
Join<Person, PersonCourse> personCourse = root.join("personCourses");
Join<PersonCourse, Course> course = personCourse.join("course");
Predicate onlySpecificCourse = builder.equal(course.get("id"), courseId);
Is this just something where I should have BOTH the @ManyToOne
field from StudentCourse to Course AND the courseId
field on StudentCourse? It looks like I can do this if I declare the courseId field as:
@Column(name = "USER_ID", insertable = false, updatable = false)
private String userId;
And then the joining becomes:
Join<Person, PersonCourse> personCourse = root.join("personCourses");
Predicate onlySpecificCourse = builder.equal(personCourse.get("courseId"), courseId);
If I do this, are there any gotchas that I should watch out for? In particular, it seems strange to have setters for both courseId
and course
on the PersonCourse
entity.