0
@Test
public void testUpdateStudent(){
    Optional<Student> student = studentRepository.findById((long) 1);
    student.setName();
}
  1. When I am using Optional I am not getting setName() method, how can I update record in my database.
  2. Also, why should I use this Optional?
Yogesh Prajapati
  • 4,770
  • 2
  • 36
  • 77

2 Answers2

0

You can use getOne(), if not willing to receive as Optional.

@Test
public void testUpdateStudent(){
    Student student = studentRepository.getOne(1L);
    student.setName();

    studentRepository.saveAndFlush(student)
}

There might be a chance of getting NullPointerException, when the record not present in DB.

When we use findById(<some_parameter>), Spring Data JPA returns an Optional object. Can get the object after isPresent() condition satisfied as follows:

@Test
public void testUpdateStudent(){
    Optional<Student> studentOpt = studentRepository.getOne(1L);
    if(studentOpt.isPresent()) {
        Student student = studentOpt.get();
        student.setName();
        studentRepository.saveAndFlush(student)
    }
}
Paramesh Korrakuti
  • 1,997
  • 4
  • 27
  • 39
0

When I am using Optional I am not getting setName() method, how can I update record in my database.

Since you are getting Optional, you can set the value in the following manner:

@Test
public void testUpdateStudent(){
    Optional<Student> student = studentRepository.findById((long) 1);
    student.get().setName();
}

Optional.get() gives you the value T present in the Optional.

Also, why should I use this Optional?

Honestly, this really depends on which type of Repository your studentRepository is extending from. You have a variety of Spring Data Repostories available like CrudRepository, PagingAndSortingRepository etc. You can arrive at a consensus after going through this official documentation.

Kavitha Karunakaran
  • 1,340
  • 1
  • 17
  • 32