【问题标题】:In Spring Data JPA FindBy method is not working and “No Property Found for Type” Exception is not occurring.在 Spring Data JPA FindBy 方法中不起作用,并且“No Property Found for Type”异常没有发生。
【发布时间】:2019-05-31 00:25:39
【问题描述】:

我是 Spring boot 和 JPA 的新手,我创建了一个简单的 JPA 存储库并尝试实现自定义 findBy 方法,但它总是返回 null,即使我在 findBy 之后使用任何虚拟名称,这不是我的类的属性不会显示任何错误。尽管默认的 findBy 方法工作正常。

package com.example.demo;

   import java.util.List;
   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.stereotype.Service;

   @Service
   public class EmployeeService {

    // This is my service class.
    // Creating employee repository
    @Autowired
    EmployeeRepo er;

    // This is the method I want to implement
    public List<Employee> getByname(String name) {

        return er.findByName(name);
    }

}

//This is my Repository 

package com.example.demo;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepo extends JpaRepository<Employee, Integer> {
        // Name is a property of Employee class
    public List<Employee> findByName(String name);
        // Dummy is not a property of Employee class
    public List<Employee> findByDummy(String name);


}

它应该给 findByDummy 方法一个错误,但它没有给出。是否将此接口视为通用接口并允许任何声明。 对于 findByName,它返回 null。它应该根据名称进行搜索,对于 findByDummy 它应该显示错误。

提前致谢。

【问题讨论】:

标签: spring rest spring-boot spring-data-jpa spring-data


【解决方案1】:

您忘记在您的存储库中添加@Repository 注释:

@Repository
public interface EmployeeRepo extends JpaRepository<Employee, Integer> {
        // Name is a property of Employee class
    public List<Employee> findByName(String name);
        // Dummy is not a property of Employee class
    public List<Employee> findByDummy(String name);


}

这应该可以解决问题。

【讨论】:

  • 谢谢!!它完成了我的工作:) 我们可以对 RepositoryRestResource 做同样的事情吗?我的意思是使用自定义查询方法?
  • 请检查这个问题——stackoverflow.com/questions/54063427/…
【解决方案2】:

@Repository 注释不是我的问题。我的问题是我认为我使用的是 URL 参数。

我的 JPA 存储库中有以下方法:

Optional<Sample> findByEpisodeId(String episodeId);

然后,我在控制器中有以下方法:

@GetMapping("/sample/{episodeId}")
    Sample getSampleBy(@PathVariable String episodeId) {
        return sampleService.findByEpisodeId(episodeId); // sampleService uses the jpa method
    }

我发送的请求是/sample/episodeId=12345

应该是/sample/12345

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2018-04-28
    • 2021-11-28
    • 2013-11-10
    • 1970-01-01
    相关资源
    最近更新 更多