Implementing Custom Methods of Spring Data Repository and Exposing Them Through Rest

Implementing custom methods of Spring Data repository and exposing them through REST

The reason these methods are not exposed is that you're basically free to implement whatever you want in custom repository methods and thus it's impossible to reason about the correct HTTP method to support for that particular resource.

In your case it might be fine to use a plain GET, in other cases it might have to be a POST as the execution of the method has side effects.

The current solution for this is to craft a custom controller to invoke the repository method.

Custom jpa repository method published by spring-data-rest

I checked the code base - seems like they have explicitily disabled custom methods - not sure why. Here is the relevant piece of code from org.springframework.data.repository.core.support.DefaultRepositoryInformation

@Override
public Set<Method> getQueryMethods() {

Set<Method> result = new HashSet<Method>();

for (Method method : getRepositoryInterface().getMethods()) {
method = ClassUtils.getMostSpecificMethod(method, getRepositoryInterface());
if (isQueryMethodCandidate(method)) {
result.add(method);
}
}

return Collections.unmodifiableSet(result);
}

/**
* Checks whether the given method is a query method candidate.
*
* @param method
* @return
*/
private boolean isQueryMethodCandidate(Method method) {
return isQueryAnnotationPresentOn(method) || !isCustomMethod(method) && !isBaseClassMethod(method);
}

How to add custom method to Spring Data JPA

You need to create a separate interface for your custom methods:

public interface AccountRepository 
extends JpaRepository<Account, Long>, AccountRepositoryCustom { ... }

public interface AccountRepositoryCustom {
public void customMethod();
}

and provide an implementation class for that interface:

public class AccountRepositoryImpl implements AccountRepositoryCustom {

@Autowired
@Lazy
AccountRepository accountRepository; /* Optional - if you need it */

public void customMethod() { ... }
}

See also:

  • 4.6 Custom Implementations for Spring Data Repositories

  • Note that the naming scheme has changed between versions. See https://stackoverflow.com/a/52624752/66686 for details.



Related Topics



Leave a reply



Submit