summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/odiparpack/back/odiparback/student/StudentService.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/com/odiparpack/back/odiparback/student/StudentService.java')
-rw-r--r--src/main/java/com/odiparpack/back/odiparback/student/StudentService.java69
1 files changed, 69 insertions, 0 deletions
diff --git a/src/main/java/com/odiparpack/back/odiparback/student/StudentService.java b/src/main/java/com/odiparpack/back/odiparback/student/StudentService.java
new file mode 100644
index 0000000..6831dd8
--- /dev/null
+++ b/src/main/java/com/odiparpack/back/odiparback/student/StudentService.java
@@ -0,0 +1,69 @@
+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<Student> getStudents() {
+ return studentRepository.findAll();
+ }
+
+ public void addNewStudent(Student student) {
+ /* check if the email is already registered, if so throw error */
+ Optional<Student> 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<Student> studentOptional = studentRepository
+ .findStudentByEmail(email);
+ if (studentOptional.isPresent()) {
+ throw new IllegalStateException("email taken");
+ }
+ student.setEmail(email);
+ }
+ }
+}