Spring Boot Rest:实现按日期查考试及特定考试平均分功能咨询
实现方案
一、Repository层扩展
1. 查询指定日期的所有考试(ExamRepository)
在已有的ExamRepository中添加基于考试日期的查询方法,Spring Data JPA会自动生成对应的SQL逻辑:
public interface ExamRepository extends JpaRepository<Exam, Long> { // 基础CRUD方法已存在,新增以下方法 List<Exam> findByExamDate(Date examDate); // 若需忽略时分秒、仅匹配日期,可使用@Query注解自定义逻辑 // @Query("SELECT e FROM Exam e WHERE DATE(e.examDate) = DATE(:examDate)") // List<Exam> findByExamDateIgnoringTime(@Param("examDate") Date examDate); }
2. 查询特定考试的平均分(GradeRepository)
在GradeRepository中添加聚合查询方法,通过JPQL实现平均分统计:
public interface GradeRepository extends JpaRepository<Grade, Long> { // 基础CRUD方法已存在,新增以下方法 @Query("SELECT AVG(g.score) FROM Grade g WHERE g.exam.id = :examId") Double findAverageScoreByExamId(@Param("examId") Long examId); }
二、Service层扩展
1. 查询指定日期考试的业务逻辑(ExamService)
封装查询逻辑,可添加空结果的兜底处理:
@Service public class ExamService { private final ExamRepository examRepository; // 构造注入已存在 public List<Exam> getExamsByDate(Date examDate) { List<Exam> exams = examRepository.findByExamDate(examDate); // 无结果时返回空列表,避免返回null return exams != null ? exams : Collections.emptyList(); } }
2. 查询考试平均分的业务逻辑(GradeService)
处理无成绩场景的空值问题,保证返回值安全:
@Service public class GradeService { private final GradeRepository gradeRepository; // 构造注入已存在 public Double getAverageScoreByExamId(Long examId) { Double average = gradeRepository.findAverageScoreByExamId(examId); // 无成绩记录时返回0.0,避免返回null引发后续空指针 return average != null ? average : 0.0; } }
三、Controller层编写GET接口
1. 查询指定日期的所有考试接口
@RestController @RequestMapping("/api/exams") public class ExamController { private final ExamService examService; // 构造注入已存在 @GetMapping("/date") public ResponseEntity<List<Exam>> getExamsByDate( @RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date examDate) { List<Exam> exams = examService.getExamsByDate(examDate); return ResponseEntity.ok(exams); } }
注:
@DateTimeFormat用于将请求参数中的字符串日期转换为Date类型,可根据实际需求调整日期格式。
2. 查询特定考试的平均分接口
@RestController @RequestMapping("/api/exams") public class ExamController { private final GradeService gradeService; // 构造注入已存在 @GetMapping("/{examId}/average-score") public ResponseEntity<Double> getExamAverageScore(@PathVariable("examId") Long examId) { Double averageScore = gradeService.getAverageScoreByExamId(examId); return ResponseEntity.ok(averageScore); } }
注:若需处理考试不存在、无成绩等异常场景,可添加全局异常处理器返回标准化错误提示。
内容的提问来源于stack exchange,提问作者zizmiz
相关产品推荐
相关产品推荐

