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 和 program 是 DTO ,如果我將 setProgram(StudyProgram) 方法更改為 setProgram(Optional) 那么它會干擾資料庫方案。解決辦法是什么?
uj5u.com熱心網友回復:
program 是可選的,使用 program.get() 獲取物件值: student.setProgram(program.get()); 在 make get() 之前,您應該檢查我們是否有結果: if(program.isPresent()) { student.setProgram(program.get());}
uj5u.com熱心網友回復:
Optional<Object>不是實際的Object。您可以使用obj.get(),如果你確保該值是出現在Optional。為了避免這種情況發生并保證空值安全,您可以使用obj.orElse(defaultValue)which 將defaultValue作為一個Object實體回傳。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/373506.html
標籤:爪哇 jpa 弹簧数据-jpa 可选的 crud-repository
上一篇:shell腳本輸出作為命令列引數傳遞的檔案夾中所有檔案的詳細資訊
下一篇:LockModeType.OPTIMISTIC和Mysql的默認隔離級別REPEATABLEREAD不能一起作業嗎?
