You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建根据部门ID获取学生信息的API

根据部门ID查询学生的API实现步骤

核心查询逻辑编写位置

你需要在departController的按ID查询方法里编写关联查询语句,以下是两种主流开发框架的具体实现示例:

场景1:Spring Boot(JPA/Hibernate)

如果使用JPA,在departController的对应方法中调用Repository层的自定义查询方法即可,核心查询逻辑定义在StudentRepository接口:

// departController.java
@GetMapping("/{deptId}/students")
public ResponseEntity<List<Student>> getStudentsByDeptId(@PathVariable Long deptId) {
    List<Student> students = studentRepository.findByDepartmentId(deptId);
    return ResponseEntity.ok(students);
}

// StudentRepository.java
public interface StudentRepository extends JpaRepository<Student, Long> {
    // JPA自动解析方法名生成SQL
    List<Student> findByDepartmentId(Long deptId);

    // 若需自定义SQL,可使用@Query注解
    @Query("SELECT s FROM Student s WHERE s.department.id = :deptId")
    List<Student> findByDepartmentIdCustom(@Param("deptId") Long deptId);
}

场景2:Node.js + Sequelize

如果使用Sequelize ORM,直接在departController的方法内编写关联查询逻辑:

// departController.js
exports.getStudentsByDeptId = async (req, res) => {
    try {
        const { deptId } = req.params;
        const students = await Student.findAll({
            where: { departmentId: deptId },
            // 如需关联联系人、批次信息,可添加include字段
            include: [Contact, Batch]
        });
        res.status(200).json(students);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
};

关键注意事项

  • 确保Student模型已定义与Department的关联外键(如departmentId)
  • 测试时请求GET /departments/{deptId}/students即可获取对应部门的学生列表

内容的提问来源于stack exchange,提问作者Ramya S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:37:14