JPA单向一对多关联无反向引用时查询学生所属课程的实现方法
单向一对多关联下查询指定学生所属课程的实现方案
当前场景为Course到Student的单向@OneToMany关联,Student实体未维护指向Course的引用,数据库student表通过course_id外键关联course表主键id,查询指定学生所属课程有以下3种常用实现方式:
- 方案1:使用JPQL关联查询(无需修改现有实体结构)
直接通过Course实体维护的students集合做关联查询,在CourseRepository中定义查询方法即可:
public interface CourseRepository extends JpaRepository<Course, Long> { // 按学生rollno查询所属课程,rollno为student表唯一主键 @Query("SELECT c FROM Course c JOIN c.students s WHERE s.rollno = :studentRollno") Optional<Course> findCourseByStudentRollno(@Param("studentRollno") Long studentRollno); }
如果你的匹配条件是学生姓名、年龄等其他字段,调整WHERE后的判断条件即可。
- 方案2:使用原生SQL查询
需要直接操作表结构查询时,可通过原生SQL实现:
public interface CourseRepository extends JpaRepository<Course, Long> { @Query(value = "SELECT c.* FROM course c INNER JOIN student s ON c.id = s.course_id WHERE s.rollno = :studentRollno", nativeQuery = true) Optional<Course> findCourseByStudentRollnoNative(@Param("studentRollno") Long studentRollno); }
- 方案3:新增Student实体的course_id映射字段(可选,适合需要频繁读取学生所属课程id的场景)
不需要修改原有关联关系,仅需在Student实体中新增course_id的普通字段映射:
@Entity public class Student { @Id private Long rollno; private String name; private Integer age; // 新增普通字段映射外键,无需配置关联注解 @Column(name = "course_id") private Long courseId; // 省略getter、setter方法 }
之后分两步查询即可:
// 1. 先根据学生唯一标识查询Student对象 Student student = studentRepository.findById(studentRollno).orElseThrow(); // 2. 根据student映射的courseId查询对应课程 Course course = courseRepository.findById(student.getCourseId()).orElseThrow();
注意:上述方法默认一个学生仅属于一个课程,如果存在一个学生关联多个课程的特殊场景,将返回值改为List<Course>即可。
内容的提问来源于stack exchange,提问作者Ritik Kaushik
相关产品推荐
相关产品推荐

