5.3. Repository Implementation

The repository implementations bring together the JPA @NamedQuery annotation (see Section 5.2, “Annotating classes with @NamedQuery) along with the QueryDefault<T> class (introduced in Section 5.1, “Background”).

For example, a CustomerRepository implementation might be:

public class CustomerRepositoryJpa implements CustomerRepository {

    public List<Customer> findCustomerById(Integer id) {
        return firstMatch(
            QueryDefault.create(
                "findCustomerById", 
                "id", id);
    }

    public List<Customer> findCustomersBySurname(String surname) {
        return allMatches(
            QueryDefault.create(
               "findCustomersBySurname", 
               "surname", surname
            ));
    }

    ...
}

The first argument for QueryDefault.create() should be the name of the query (it doesn't need to be the same as the method name, but that's a sensible convention to follow). The remaining arguments go in pairs, alternating between the parameter name and the argument value. For example, the ":id" in the @NamedQuery annotation corresponds to the second argument "id" in the call to QueryDefault.create().