以下代码仅供演示之用。
我的实体 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 上添加过滤器
答案 0 :(得分:11)
List<Employee> findByEmployeeKeyEmployeeIdAndEmployeeKeyDepartmentName(int Id,String name);
答案 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));
详细说明了搜索结果