服務層用於封裝業務邏輯,讓應用的其他部分可以不直接與數據層交互,而是通過服務層進行調用。
StudentService 是應用的業務層核心。它通過 StudentRepository 與數據層進行交互,以提供業務功能。
package com.example.demo.student;
import jakarta.transaction.Transactional;
import jdk.jfr.TransitionTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class StudentService {
private final StudentRepository studentRepository;
@Autowired
public StudentService(StudentRepository studentRepository){
this.studentRepository = studentRepository;
}
public List<Student> getStudents() {
return studentRepository.findAll();
}
@PostMapping
public void addNewStudent( Student student) {
Optional<Student> studentOptional = studentRepository
.findStudentByEmail(student.getEmail());
if (studentOptional.isPresent()) {
throw new IllegalStateException("email token");
}
studentRepository.save(student);
}
public void deletStudent(Long studentId) {
boolean exists = studentRepository.existsById(studentId);
if (!exists) {
throw new IllegalStateException("student with id" + studentId + "dose not exists");
}
studentRepository.deleteById(studentId);
}
@Transactional
public void updateStudent(Long studentId,
String name,
String email) {
Student student = studentRepository.findById(studentId)
.orElseThrow(() -> new IllegalStateException(
"student with ID" + studentId + "does not exist"
));
if(name != null && name.length() > 0 && !Objects.equals(student.getName(), name)) {
student.setName(name);
}
if (email != null &&
email. length() > 0 &&
Objects .equals (student. getEmail(), email)) {
Optional<Student> student0ptional = studentRepository.findStudentByEmail(email);
if (student0ptional.isPresent()) {
throw new IllegalStateException("email taken");
}
student.setEmail(email);
}
}
}
此服務層提供 CRUD 操作,並包含其他業務邏輯,例如檢查郵件唯一性。