[英]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.学生和程序是 DTO,如果我将 setProgram(StudyProgram) 方法更改为 setProgram(Optional),那么它会干扰数据库方案。 what will be the solution?
解决方案是什么?
program is Optional, use program.get() for getting object value: student.setProgram(program.get()); program 是可选的,使用 program.get() 获取 object 值: student.setProgram(program.get());
Optional<Object>
is not the actual Object
. Optional<Object>
不是实际的Object
。 You can use obj.get()
if you're sure that the value is present in the Optional
.如果您确定该值存在于
Optional
中,则可以使用obj.get()
。 To avoid such an occurrence and be null safe, you can use obj.orElse(defaultValue)
which will return the defaultValue
as an Object
instance.为避免这种情况发生并确保 null 安全,您可以使用
obj.orElse(defaultValue)
将defaultValue
作为Object
实例返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.