EzyJPA: Custom Query Result

Updated at 1691032345000
Sometimes you don't want to select entire entity. EzyJPA will help you map query result to a result class.

1. Query

Let's say we have query method like this:

    @EzyQuery(
        value = "select employeeId, firstName from ezyfox_jpa_employee where employeeId = ?0",
        nativeQuery = true
    )
    Optional<Employee> findEmployeeIdAndFirstNameByEmployeeIdOptional(
        String employeeId
    );

Let's focus on select employeeId, firstName, we select 2 fields in camel case.

2. Result class

With 2 above fields, we will need create a class with 2 fields same name and same order, example:

    @Getter
    @Setter
    @EzyQueryResult
    public class EmployeeIdAndFirstNameResult {
        private String employeeId;
        private String firstName;
    }

Don't for get @EzyQueryResult annotation, EzyJPA will need this annotation to recognize the result class and create deserializer class for it.

3. Use cases

You can use request class in 3 cases:

  • Find one nullable result, example: EmployeeIdAndFirstNameResult findEmployeeIdAndFirstNameByEmployeeId
  • Find one optional result, example: Optional<Employee> findEmployeeIdAndFirstNameByEmployeeIdOptional
  • Fine a list result, example: List<Employee> findEmployeeIdAndFirstNameListByEmployeeId

Next

You can see how to connect to multi datasources.