弹簧数据 JPA 无法找到具有给定名称的属性

2022-09-01 04:26:13

我试图使用,我不断得到错误,我无法弄清楚问题是什么:Spring Data JPASpring Boot

无法在此托管类型上找到具有给定名称 [firstName] 的属性 [com.example.h2demo.domain.Subscriber]

名字是在我的实体类中声明的。我之前在不同的项目中使用过DAO的服务类,并且工作得很好。

我的实体类(getters和setter也在类中):

        @Entity
        public class Subscriber {

        @Id @GeneratedValue
        private long id;
        private String FirstName,LastName,Email;

        public Subscriber(long id, String firstName, String lastName, String email) {
            this.id = id;
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Email = email;
          }
        }
...

我的存储库类

@Component
public interface SubscriberRepository extends JpaRepository<Subscriber,Long> {
    Subscriber findByFirstName(String FirstName);
    Subscriber deleteAllByFirstName(String FirstName);
}

我的服务等级

@Service
public class SubscriberService {

    @Autowired
    private SubscriberRepository subscriberRepository;

    public Subscriber findByFirstName(String name){
        return  subscriberRepository.findByFirstName(name);

    }

    public Subscriber deleteAllByFirstName(String name){
        return  subscriberRepository.deleteAllByFirstName(name);

    }

    public void addSubscriber(Subscriber student) {
        subscriberRepository.save(student);
    }
}

和我的控制器类:

@RestController
@RequestMapping("/subscribers")
public class SubscriberController {

    @Autowired
    private SubscriberService subscriberService;

    @GetMapping(value = "/{name}")
    public Subscriber findByFirstName(@PathVariable("name") String fname){
        return  subscriberService.findByFirstName(fname);
    }

    @PostMapping( value = "/add")
    public String insertStudent(@RequestBody final Subscriber subscriber){
        subscriberService.addSubscriber(subscriber);
        return "Done";
    }

}

答案 1

尝试更改为private String FirstName,LastName,Email;private String firstName,lastName,email;

它应该有效。

findByFirstName试图按照惯例找到一个不存在的领域。SubscriberRepository firstName

有关如何遍历实体内属性的进一步参考 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions


答案 2

同样的问题是当我处理弹簧数据规范(https://www.baeldung.com/rest-api-search-language-spring-data-specifications)

最初的代码片段是:

private Specification<Project> checkCriteriaByProjectNumberLike(projectNumber: String) {
    (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("project_number"), "%" + projectNumber)
}

问题出在 root.get(“project_number”)。在方法中,我必须像在模型(projectNumber)中一样放置字段名称,但是我发送了数据库中的字段名称(project_number)。

也就是说,最终的正确决定是:

private Specification<Project> checkCriteriaByProjectNumberLike(projectNumber: String) {
    (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("projectNumber"), "%" + projectNumber)
}

推荐