Java – Spring JPA – Find By EmbeddedId partially

hibernatejavajpaspring-data-jpa

Below code is for demo purpose only.

My Entity bean looks like this

@Entity
class Employee {

    @EmbeddedId
    private EmployeeKey employeeKey;

    private String firstName;
    private String lastName;

    // Other fields
    // Getter and Setters
}

The Embeddable class:

@Embeddable
class EmployeeKey implements Serializable {

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

    //Getter and Setters
}

I can write JPARepository interface method to find Employees by the EmbeddedId that returns me results as well.

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

Question:
Suppose, while querying I have employeeId and branchName only, and I don't want to put filter on departmentName

  • In such cases how can I write my Repository method
  • Does JPA have something in-build for such scenario?

Best Answer

List<Employee> findByEmployeeKeyEmployeeIdAndEmployeeKeyBranchName(
        int employId,
        String branchName);

Should work Have a look at query derivation