简体   繁体   English

findbyID 返回可选。 将此 object 设置为另一个 object 会导致错误

[英]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.

相关问题 为什么 findById 响应未找到 id 但 findAll 使用此 id 返回 object - Why findById response is id not found but findAll returns object with this id 使用Mockito返回Java 8可选对象的模拟对象返回Empty Optional - Mocking Object that returns Java 8 Optional Object with Mockito returns Empty Optional WrongTypeOfReturnValue:findById()无法返回“对象” - WrongTypeOfReturnValue: “Object” cannot be returned by findById() findbyid object spring 启动和更新 - findbyid object spring boot and update 转换一个可选<list<object> > 到另一个可选<list<object> > 在 Java </list<object></list<object> - Convert one Optional<List<Object>> to another Optional<List<Object>> in Java 设置作为另一个对象的子对象的对象的字段值 - Setting a field value of an object that is a child of another object 设置一个新对象等于另一个特定对象 - Setting a new object equal to another specific object Java 将 Optional&lt;&gt; 映射到对象而不是另一个对象的现有方法? - Existing way to Java map Optional<> onto object instead of to another object? 设置对象数组值时出错 - Error Setting Object Array Values 为什么 spring 数据 redis findById 在升级到版本 2.3.2.RELEASE 后在 Optional 中返回 null 值 - Why spring data redis findById returns null values in Optional after upgrading to version 2.3.2.RELEASE
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM