package com.odiparpack.back.odiparback.student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; 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 getStudents() { return studentRepository.findAll(); } public void addNewStudent(Student student) { /* check if the email is already registered, if so throw error */ Optional studentOptional = studentRepository.findStudentByEmail(student.getEmail()); if (studentOptional.isPresent()) { throw new IllegalStateException("email taken"); // email validation is also possible here } studentRepository.save(student); } public void deleteStudent(Long studentId) { boolean exists = studentRepository.existsById(studentId); if (!exists) { throw new IllegalStateException( "student with id " + studentId + " does not exists"); } studentRepository.deleteById(studentId); } // "The entity goes into a managed state". Changes are seaved automatically @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" )); /* check that attributes are valid before updating object/record */ if (name != null && name.length() > 0 && !Objects.equals(student.getName(), name)) { student.setName(name); } if (email != null && email.length() > 0 && !Objects.equals(student.getName(), email)) { Optional studentOptional = studentRepository .findStudentByEmail(email); if (studentOptional.isPresent()) { throw new IllegalStateException("email taken"); } student.setEmail(email); } } }