public String addStudyProgram(){
Optional<StudyProgram> program = studyProgramRepository.findById(1);
Student student = new Student();
student.setStudentName("Mushashi");
student.setProgram(program); // error The method setProgram(StudyProgram) in the type Student is not applicable for the arguments (Optional<StudyProgram>)
return "Done";
}
student and program are DTO , if i change setProgram(StudyProgram) method to setProgram(Optional) then it interfere with database scheme. what will be the solution ?
CodePudding user response:
program is Optional, use program.get() for getting object value : student.setProgram(program.get());
CodePudding user response:
Optional<Object>
is not the actual Object
. You can use obj.get()
if you're sure that the value is present in the Optional
. To avoid such an occurrence and be null safe, you can use obj.orElse(defaultValue)
which will return the defaultValue
as an Object
instance.