Spring JPA - 部分由EmbeddedId查找

时间:2017-05-09 08:42:07

标签: java hibernate jpa spring-data-jpa

以下代码仅供演示之用。

我的实体 bean看起来像这样

@Entity
class Employee {

    @EmbeddedId
    private EmployeeKey employeeKey;

    private String firstName;
    private String lastName;

    // Other fields
    // Getter and Setters
}

Embeddable 类:

@Embeddable
class EmployeeKey implements Serializable {

    private int employeeId;
    private String branchName;
    private String departmentName;

    //Getter and Setters
}

我可以编写 JPARepository 接口方法来查找EmbeddedId的Employees,它也会返回结果。

interface EmployeeRepository extends JpaRepository<Employee, EmployeeKey> {
        List<Employee> findByEmployeeKey(EmployeeKey employeeKey);
}

问题: 假设,在查询时我只有 employeeId branchName ,而我不想在 departmentName 上添加过滤器

  • 在这种情况下,我该如何编写我的Repository方法
  • JPA是否为这种情况提供内置服务?

2 个答案:

答案 0 :(得分:11)

List<Employee> findByEmployeeKeyEmployeeIdAndEmployeeKeyDepartmentName(int Id,String name);

应该有效Have a look at query derivation

答案 1 :(得分:5)

以下是它对我的影响。

@Ketrox的答案是绝对正确的,并且运行正常。但在我的真实场景中,我有6个字段可供搜索,并且导致120个字符长的方法名称。 (如下所示

List<Employee> findByEmployeeKeyField1AndEmployeeKeyField2AndEmployeeKeyField3AndEmployeeKeyField4AndEmployeeKeyField5AndEmployeeKeyField6(String field1, String field2, String field3, String field4, String field5, String field6);

这当然不够好,不足以让codenarc感到不快。

最后,我通过示例使用find,结果证明这是非常愉快的解决方案。

<强> 存储库:

//skipped lines    
import org.springframework.data.domain.Example
//skipped lines
interface EmployeeRepository extends JpaRepository<Employee, EmployeeKey>{
    List<Employee> findAll(Example<Employee> employee);
}

<强> 用法:

// Prepare Employee key with all available search by keys (6 in my case)
EmplyeeKey key = new EmplyeeKey();
key.setField1("field1_value");
key.setField2("field2_value");
//Setting remaining 4 fields

// Create new Employee ans set the search key
Employee employee = new Employee();
employee.setEmployeeKey(key);


// Call the findAll by passing an Example of above Employee object
List<Employee> result = employeeRepository.findAll(Example.of(employee));

我已按Spring Data JPA find by @EmbeddedId Partially

详细说明了搜索结果