m_jdm35
m_jdm35

Reputation: 131

Can I use a @RequestParam as a @Query parameter when using Spring Data Rest?

I'm using Spring Data Rest, my Repository extends JpaRepository and I want to create a custom query with @Query.

My method parameter is a @RequestParameter and I want to use it as a parameter for the query:

@Query("SELECT u FROM User u WHERE u.name = :search")
List<User> findBySearch(@RequestParam("search") @Param("search") String search);

Can I use the @RequestParam as parameter for the query?

Upvotes: 0

Views: 163

Answers (1)

İsmail Y.
İsmail Y.

Reputation: 3965

The parameter is the variable that is defined in a functional block. So, it is basically used whenever we need to pass a value to a particular functional block.

Depending on this; even if you could use @RequestParam, you would have to send this value when you call this method.

I'm not sure that getting the value using this is what you want.

You can try to get the request parameter directly:

Spring support the usage of restricted SpEL template expressions in manually defined queries that are defined with @Query.

You can create custom EvaluationContextExtension to use request parameters directly in @Query.

@Component
public class RequestEvaluationContextExtension
        implements EvaluationContextExtension {

    private final HttpServletRequest httpServletRequest;

    public RequestEvaluationContextExtension(
            HttpServletRequest httpServletRequest) {
        this.httpServletRequest = httpServletRequest;
    }

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> properties = new HashMap<>(
                EvaluationContextExtension.super.getProperties());
        return properties;
    }

    @Override
    public String getExtensionId() {
        return "request";
    }

    @Override
    public Object getRootObject() {
        return httpServletRequest;
    }
}

Usage in query should be like this:

@Query("SELECT u FROM User u WHERE u.name  = ?#{request.getParameter('search')}")
List<User> findBySearchParameter();

You can call this repository method without sending any arguments.

If your http request has a search parameter (eg: http://localhost:8080/test?search=foobar) You create a query based on the value of this parameter.

Upvotes: 1

Related Questions