summaryrefslogtreecommitdiff
path: root/src/main/java/com/stileeducation/markr/service/StudentService.java
blob: e49f06af9372cacc12f1d7af4d6df99a099474e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.stileeducation.markr.service;

import com.stileeducation.markr.entity.Student;
import com.stileeducation.markr.repository.StudentRepository;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class StudentService {

  private final StudentRepository studentRepository;

  public StudentService(StudentRepository studentRepository) {
    this.studentRepository = studentRepository;
  }

  @Transactional
  public Student findOrCreateStudent(String firstName, String lastName, String studentNumber) {
    Optional<Student> optionalStudent = studentRepository.findByStudentNumber(studentNumber);
    if (optionalStudent.isPresent()) {
      Student student = optionalStudent.get();
      // Reset transients
      student.setCreated(false);
      student.setUpdated(false);
      return student;
    } else {
      Student student = new Student();
      student.setFirstName(firstName);
      student.setLastName(lastName);
      student.setStudentNumber(studentNumber);
      student.setCreated(true);
      return studentRepository.save(student);
    }
  }
}