Employee 类型未定义方法 orElseThrow(() -> {})

The method orElseThrow(() -> {}) is undefined for the type Employee

在为员工 CRUD 操作创建 Spring 引导控制器时,我尝试使用 orElseThrow 方法但给出错误 The method orElseThrow(() -> {}) is undefined for the type Employee。谁能帮我解决这个问题。


package com.mkknowledge.managerportal.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import com.mkknowledge.managerportal.model.Employee;
import com.mkknowledge.managerportal.service.EmployeeService;
import com.mkknowledge.managerportal.exception.ResourceNotFoundException;

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping({ "/employees" })
public class EmployeeController {
    
    @Autowired
    private EmployeeService employeeService;
    
    
    @GetMapping(produces = "application/json")
    public List<Employee> listEmployee() {
        return employeeService.listAll();
    }
    

    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable(value = "id") Long id) {
        
        Employee emp = employeeService.get(id)
                .orElseThrow(() -> new ResourceNotFoundException("Employee", "id", id));
        
        employeeService.delete(id);

        return ResponseEntity.ok().build();
    }

}

我还创建了自定义 ResourceNotFoundException class 来处理异常。


public ResourceNotFoundException(String resourceName, String fieldName, Object fieldValue) {
        super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue));
        this.resourceName = resourceName;
        this.fieldName = fieldName;
        this.fieldValue = fieldValue;
    }


已添加员工 Class 以供进一步参考


package com.mkknowledge.managerportal.model;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import javax.persistence.JoinColumn;

import com.fasterxml.jackson.annotation.JsonFormat;

@Entity
@Table( name = "employee",
uniqueConstraints = {@UniqueConstraint(columnNames = "email")})
public class Employee {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long empId;
    
    @NotBlank
    @Size(max = 20)
    private String firstname;
    
    @NotBlank
    @Size(max = 20)
    private String lastname;
    
    @NotBlank
    @Size(max = 50)
    @Email
    private String email;
    
    @NotBlank
    @Size(max = 120)
    private String address;
    
    @JsonFormat(pattern="yyy-mm-dd")
    private Date dob;
     
    @NotBlank
    @Size(max = 10)
    private String mobile;
    
    @NotBlank
    @Size(max = 20)
    private String city;
    
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable( name = "user_roles", 
        joinColumns = @JoinColumn(name = "user_id"), 
        inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();
    
    public Employee() {
        
    }
    
    public Long getEmpId() {
        return empId;
    }



    public void setEmpId(Long empId) {
        this.empId = empId;
    }



    public String getEmail() {
        return email;
    }



    public void setEmail(String email) {
        this.email = email;
    }



    public Set<Role> getRoles() {
        return roles;
    }



    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    
    
    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((address == null) ? 0 : address.hashCode());
        result = prime * result + ((city == null) ? 0 : city.hashCode());
        result = prime * result + ((dob == null) ? 0 : dob.hashCode());
        result = prime * result + ((empId == null) ? 0 : empId.hashCode());
        result = prime * result + ((firstname == null) ? 0 : firstname.hashCode());
        result = prime * result + ((lastname == null) ? 0 : lastname.hashCode());
        result = prime * result + ((mobile == null) ? 0 : mobile.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (city == null) {
            if (other.city != null)
                return false;
        } else if (!city.equals(other.city))
            return false;
        if (dob == null) {
            if (other.dob != null)
                return false;
        } else if (!dob.equals(other.dob))
            return false;
        if (empId == null) {
            if (other.empId != null)
                return false;
        } else if (!empId.equals(other.empId))
            return false;
        if (firstname == null) {
            if (other.firstname != null)
                return false;
        } else if (!firstname.equals(other.firstname))
            return false;
        if (lastname == null) {
            if (other.lastname != null)
                return false;
        } else if (!lastname.equals(other.lastname))
            return false;
        if (mobile == null) {
            if (other.mobile != null)
                return false;
        } else if (!mobile.equals(other.mobile))
            return false;
        return true;
    }
    
    
}


员工服务获取方法


    public Employee get(long id) {
        return employeeRepository.findById(id).get();
    }

tl;博士

变化:

return employeeRepository.findById( id ).get() ;

…至:

return employeeRepository.findById( id ) ;

…同时将 return 类型的声明从 Employee 更改为 Optional< Employee >

Optional< Employee >

显然你指的是 orElseThrow method of the Optional class。 Optional class 是对象引用的包装器。 Optional 对象要么包含有效载荷(对另一个对象的引用),要么什么都不包含。

Optional 的目的是使 returning a null 合法的情况变得明显(相对于错误情况)。返回一个 Optional 消除了 returning a null 的歧义,我们不知道是否 (a) 根本没有可用的值来 returned,或者如果 (b ) 作为失败信号发送的 null 出了点问题。在现代 Java 中,(a) 场景最好用 Optional 类型的对象来表示,而 (b) 场景最好用抛出异常来表示。

您的代码:

Employee emp = 
    employeeService
        .get(id)
        .orElseThrow( () -> new ResourceNotFoundException("Employee", "id", id ) );

… 仅当调用 employeeService 对象的 get(id) 方法 returned 类型为 Optional< Employee > 的对象时才有效。根据您的报告,显然情况并非如此。

我猜你的 get(id) 调用 return 是一个 Employee 对象而不是 Optional< Employee > 对象。

确实如此,如果您的代码:

    // `EmployeeService` class
    public Employee get( long id ) {
        return employeeRepository.findById( id ).get() ;
    }

… 是你的 EmployeeService 方法的一个方法。该代码正在调用 findById( id ),显然 return 是 Optional< Employee >。问题是该方法继续调用 get.

解决方案:在 EmployeeService#get 方法中删除对 get 的调用。只是 return Optional< Employee > 对象 return 由 findById 调用编辑。所以你的代码看起来像这样:

    // `EmployeeService` class
    public Optional< Employee > get( long id ) {
        return employeeRepository.findById( id ) ;
    }

大局可以用 来解释。