29
votes

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?
2
@Zeromus Thanks for the link. However, I am not in favour of writing repository implementation. I am wondering if I can make use of built-in functionality to address the questionAmit Phaltankar

2 Answers

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

Should work Have a look at query derivation

12
votes

Here is how it worked for me.

@Ketrox's answer is absolutely correct and works fine. But in my real scenario I had 6 fields to search by and which resulted in an 120+ characters long method name. (Something like below)

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

Which is certainly not good enough to read and more than good enough to make codenarc unhappy.


Finally I used find by example and that turned out to be really pleasant solution.

Repository:

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

Usage:

// 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));

I have elaborated the search by Spring Data JPA find by @EmbeddedId Partially