【问题标题】:JPA CrudRepository for findIn method用于查找方法的 JPA CrudRepository
【发布时间】:2016-09-15 16:55:00
【问题描述】:

在一个要求中,我需要按 id 在列表中查找。下面是例子。

class Employee{
   Long id;
   Contractor contractor;
}
class Contractor {
   Long id;
   List<Address> addressList;
}
class Address {
   Long id;
   String line;
}

现在在 EmployeeController.java 类中,我需要通过员工 ID 和地址 ID 来查找。

我有 CrudRepository 如下。

interface EmployeeRepository extends CrudRepository<Employee, Long> {
   Employee findOne(Long id);

   // I want one method here that can find by employee id and address id.
   Employee findByIdAndAddress(); 
}

当我尝试运行 spring 应用程序时,它给出了以下异常。

PropertyReferenceException:找不到类型 Employee 的属性地址!

谢谢!

【问题讨论】:

  • 如果没有定义员工和地址之间的映射,如何通过地址找到员工?
  • 我想目的是找到一个Employee,其中有一个Contractor,而Address又是一个匹配的Address

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


【解决方案1】:

好吧,异常本身很清楚,它试图在Employee 上找到一个不存在的属性“地址”,因此您必须加入ContractorAddress 才能使其工作。但是,据我在reserved keywords 列表中看到的,您无法通过方法命名来做到这一点。

所以解决办法是自己写查询,例如:

@Query("SELECT e FROM Employee e JOIN e.contractorList c JOIN c.addressList a " +
       "WHERE e.id = :id AND a.id = :addressId")
Employee findByIdAndAddress(@Param("id") Long id, @Param("addressId") Long addressId); 

【讨论】:

    猜你喜欢
    • 2020-02-09
    • 1970-01-01
    • 2021-08-21
    • 2017-07-04
    • 2019-03-17
    • 2017-08-21
    • 2017-09-18
    • 2020-04-02
    • 2018-05-12
    相关资源
    最近更新 更多