由于篇幅所限,我将提供一个简化版的学生信息管理系统的Spring Boot后端部分的核心代码示例。
// StudentController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/students")
public class StudentController {
private final StudentService studentService;
@Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
@GetMapping
public List<Student> getAllStudents() {
return studentService.findAll();
}
@GetMapping("/{id}")
public Student getStudentById(@PathVariable(value = "id") Long studentId) {
return studentService.findById(studentId);
}
@PostMapping
public Student createStudent(@RequestBody Student student) {
return studentService.save(student);
}
@PutMapping("/{id}")
public Student updateStudent(@PathVariable(value = "id") Long studentId, @RequestBody Student studentDetails) {
return studentService.update(studentId, studentDetails);
}
@DeleteMapping("/{id}")
public void deleteStudent(@PathVariable(value = "id") Long studentId) {
studentService.deleteById(studentId);
}
}
// StudentService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class StudentService {
private final StudentRepository studentRepository;
@Autowired
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public List<Student> findAll() {
return studentRepository.findAll();
}
public Student findById(Long id) {
Optional<Student> student = studentRepository.findById(id);
return student.orElse(null);
}
public Student save(Student student) {
return studentRepository.save(student);
}
public Student update(Long id, Student studentDetails) {
Student student = findById(id);
if (student != null) {
// 更新student对象的属性
// student.set...
}
return studentRepository.save(student);
}
public void deleteById(Long id) {
studentRepository.deleteById(id);
}
}
// Student.java (假设这是一个实体类)
pu