【问题标题】:Inferred type 'S' for type parameter 'S' is not within its bound; should extend 'com.example.srilanka.model.Employee'类型参数“S”的推断类型“S”不在其范围内;应该扩展“com.example.srilanka.model.Employee”
【发布时间】:2019-02-23 12:54:13
【问题描述】:

我在参与 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> {

}

【问题讨论】:

  • 请贴出你的EmployeeRepository类的源代码。我相信它可以帮助您解决问题。

标签: java spring-boot


【解决方案1】:

从文档findOne 返回Optional&lt;S&gt;

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 引发异常。

【讨论】:

  • 在没有先调用 isPresent() 的情况下使用 employeeRepository.findOne(empId).get() 是很危险的,因为如果找不到实体,它可能会引发 NullPointerException
  • @amseager 你是对的,在这种情况下你可以使用orElse(null)orElseThrow
【解决方案2】:

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

这个方法在CrudRepository之前的签名是:

T findOne(ID id);

现在(从 2.0 版本开始)它变成了(QueryByExampleExecutor):

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

但别担心 - 您可以使用来自 CrudRepositoryOptional&lt;T&gt; findById(ID id);

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多