Spring JPA - Partially EmbeddedId Search

The code below is for demonstration purposes only.

My Entity bean is as follows

@Entity
class Employee {

    @EmbeddedId
    private EmployeeKey employeeKey;

    private String firstName;
    private String lastName;

    // Other fields
    // Getter and Setters
}

Inline class:

@Embeddable
class EmployeeKey implements Serializable {

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

    //Getter and Setters
}

I can write a JPARepository interface method to find Employees using the EmbeddedId, which also returns the results to me.

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

Question: Suppose when I request, I only have employeeId and branchName, and I don’t want to put a filter in departmentName

  • In such cases, how can I write a repository method
  • Does JPA have something built-in for this scenario?
+13
source share
2 answers

Here's how it works for me.

@Ketrox . 6 , 120+. (- )

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

, , , .


find by example, .

Repository:

//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 @EmbeddedId

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

+9

Source: https://habr.com/ru/post/1017096/


All Articles