Search code examples
javajpaspring-data-jpaoption-typecrud-repository

findbyID returns optional . setting this object to another object cause error


    
    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 ?


Solution

  • program is Optional, use program.get() for getting object value : student.setProgram(program.get()); Before make get(), you should check if we have a result: if(program.isPresent()) { student.setProgram(program.get());}