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
Preparedstatement Syntax Error
How to Select an Item from a Dropdown List Using Selenium Webdriver with Java
Reverse Java Graphics2D Scaled and Rotated Coordinates
Execute Jar File with Multiple Classpath Libraries from Command Prompt
How to Use Collections.Sort() in Java
How to Create a Static Local Variable in Java
How to Handle It with Scanner (Java)
How to Enable the Java Keyword Assert in Eclipse Program-Wise
In Java Critical Sections, What Should I Synchronize On
What Is the Point of Getters and Setters
How to Send List of Objects to View and Back to Post Method in Controller
Superclass Reference Not Able to Call Subclass Method in Java
Merging Two JSON Documents Using Jackson
How to Achieve Transfer File Between Client and Server Using Java Socket