@Test(expected = ResourceAlreadyExistsException.class) public void testInsertExistingStudent() throws ResourceAlreadyExistsException { Student student1 = new Student(1234, "John Doe", LocalDate.of(2011, Month.JANUARY, 1)); Student student2 = new Student(1234, "Jane Doe", LocalDate.of(2012, Month.MAY, 1)); try { Student insertedStudent = studentService.insertStudent(student1); assertEquals(student1, insertedStudent); } catch (ResourceAlreadyExistsException e) { e.printStackTrace(); } Student insertedStudent = studentService.insertStudent(student2); assertEquals(student2, insertedStudent); }
public Student insertStudent(Student student) throws ResourceAlreadyExistsException { Optional<Student> optionalStudent = studentRepository.findById(student.getId()); if (optionalStudent.isPresent()) { throw new ResourceAlreadyExistsException(student.getId() + ""); } else { return studentRepository.save(student); } }
StudentService { public Student insertStudent(Student student) throws ResourceAlreadyExistsException { Optional<Student> optionalStudent = studentRepository.findById(student.getId()); if (optionalStudent.isPresent()) { throw new ResourceAlreadyExistsException(student.getId() + ""); } else { return studentRepository.save(student); } } }
StudentService { public Student insertStudent(Student student) throws ResourceAlreadyExistsException { Optional<Student> optionalStudent = studentRepository.findById(student.getId()); if (optionalStudent.isPresent()) { throw new ResourceAlreadyExistsException(student.getId() + ""); } else { return studentRepository.save(student); } } StudentService(StudentRepository studentRepository); }
StudentService { public Student insertStudent(Student student) throws ResourceAlreadyExistsException { Optional<Student> optionalStudent = studentRepository.findById(student.getId()); if (optionalStudent.isPresent()) { throw new ResourceAlreadyExistsException(student.getId() + ""); } else { return studentRepository.save(student); } } StudentService(StudentRepository studentRepository); Student findById(long id); List<Student> findAll(); boolean deleteById(long id); Student insertStudent(Student student); Student updateStudent(long id, Student student); }
StudentService { public Student insertStudent(Student student) throws ResourceAlreadyExistsException { Optional<Student> optionalStudent = studentRepository.findById(student.getId()); if (optionalStudent.isPresent()) { throw new ResourceAlreadyExistsException(student.getId() + ""); } else { return studentRepository.save(student); } } StudentService(StudentRepository studentRepository); Student findById(long id); List<Student> findAll(); boolean deleteById(long id); Student insertStudent(Student student); Student updateStudent(long id, Student student);  }