【问题标题】:The method findOne(Long) is undefined for the type PersonRepository [duplicate]未定义 PersonRepository 类型的方法 findOne(Long) [重复]
【发布时间】:2019-12-02 16:30:15
【问题描述】:

我正在尝试使用 Spring boot 构建简单的博客应用程序。但是,当我尝试将 findOne 用于我的 service.java 时,我遇到了“方法 findOne(Long) 未定义类型 PersonRepository”的问题。以下是我所做的

我试图在存储库中创建指示 findOne 和保存的对象。但是它没有帮助

PersonRepository.java

package PersonRepository.javaio.javabrains.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import io.javabrains.Entity.Person;
@Repository
public interface PersonRepository extends CrudRepository<Person,Long>{

public Person findByEmail(String email);

    /*
     * public Person findOne(Long id);
     * 
     * public Iterable<Person> findAll();
     * 
     * public Person save(Person person);
     */

PersonService.java

@Service
public class PersonService {

    @Autowired
    private PersonRepository personRepository;

    public Object findAll(){
        return personRepository.findAll();
    }

    public Person findById(Long id){
        return personRepository.findOne(id);
    }

我希望消除评论块可以解决问题。但是,当我尝试运行该应用程序时,它会显示错误

【问题讨论】:

    标签: java spring spring-boot web


    【解决方案1】:

    最好使用JpaRepository(它扩展了 CRUD 存储库)

    您可以使用 getOne()findById() (可选)

    findById()

    通过 id 检索实体。

    参数:id不能为空。

    返回:具有给定 id 的实体或 Optional#empty() 如果没有找到

    抛出:IllegalArgumentException - 如果 id 为空。

    getOne()

    返回对具有给定标识符的实体的引用。取决于 关于如何实现 JPA 持久性提供程序,这很可能 总是返回一个实例并抛出一个 首次访问时出现 javax.persistence.EntityNotFoundException。一些 他们将立即拒绝无效的标识符。

    参数:id不能为空。

    返回:对具有给定标识符的实体的引用。

    【讨论】:

      【解决方案2】:

      请检查您使用的 Spring 版本。可能是你的findOnefindById替换了。

      因此,您的存储库将变为:

      public Person findByEmail(String email);
      
      
           public Person findById(Long id);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        • 2017-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多