类型参数“ S”的推断类型“ S”不在其范围内;应该扩展'com.example.srilanka.model.Employee'

时间:2019-02-23 12:54:14

标签: java spring-boot

在使用Spring Boot项目时遇到上述错误(Inferred type 'S' for type parameter 'S' is not within its bound; should extend 'com.example.srilanka.model.Employee')。我已经在stackoverflow以及其他教程中引用了该主题下的所有文章。但是我还没有找到解决方案。

package com.example.srilanka.dao;
import com.example.srilanka.model.Employee;
import com.example.srilanka.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class EmployeeDAO {

    @Autowired
    EmployeeRepository employeeRepository;

    /*to save an employee*/


    public Employee save(Employee emp){
        return employeeRepository.save(emp);
    }

    /*search all employees*/
    public List<Employee> findAll(){
        return employeeRepository.findAll();
    }

    /*update an employee by id*/

    public Employee findOne(int empId){
        return employeeRepository.findOne(empId);  /*<----------error arise in here
    }

    /*get an employee*/

    /*delete an emmployee*/
}

我的EmployeeRepository在这里

package com.example.srilanka.repository;

import com.example.srilanka.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {

}

2 个答案:

答案 0 :(得分:3)

从文档findOne中返回Optional<S>

public <S extends T> Optional<S> findOne(Example<S> example)

因此,您可以通过两种方式.orElse(null)来获得对象,或者如果对象不存在,则返回null:

return employeeRepository.findOne(empId).orElse(null);

否则将您的方法类型更改为Optional

public Optional<Employee> findOne(int empId) {
    return employeeRepository.findOne(empId);
}

或者如果对象不存在,甚至可以使用orElseThrow引发异常。

答案 1 :(得分:2)

我想您已经更新了Spring-data-jpa依赖性。

此方法在CrudRepository中的先前签名为:

T findOne(ID id);

现在(自2.0版开始)它变为(在QueryByExampleExecutor中):

<S extends T> Optional<S> findOne(Example<S> example);

但是请放心-您可以使用Optional<T> findById(ID id);中的CrudRepository

相关问题