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.