Home > Back-end >  How to use @ReqeustBody with the @Query
How to use @ReqeustBody with the @Query

Time:12-30

I'm using a @Query Annotation to SELECT data out of my Database, but I want to add a Parameter to the SQL Query, to input data from a Request Body. I don't know how to do that and can't find an example.

For Example, I have an abstract method inside my Repository:

@Query(value= "SELECT * FROM planets WHERE color= :body.getColor()", nativeQuery=true)
Iterable<Planet> getBody(Planet body);

And the Method in the Controller Class would look something like this:

@GetterMapping("/body")
Iterable<Planet> getBody(@ReqeustBody Planet body( { return Repository.getBody(body); }

In Postman I would do something like this:

GET |  http://localhost:8080/body | Body | raw | JSON: {"color":"red"}

Obviously this does not work and gives me error:

org.hibernate.QueryException: Named parameter not bound : body.getColor()

My question is how would the syntex be like implementing a ReqeustBody into a @Query?

CodePudding user response:

Do it simple way

@Query(value= "SELECT * FROM planets WHERE color=:color", nativeQuery=true)
Iterable<Planet> getBody(String color);

and pass color instead of Planet

return Repository.getBody(body.getColor())

It is possible to create custom extension to spring repository that would accept some abstract HavingColor object in general, but it requires some boilerplate code (not that much) and is just not worth of an effor (in the result, you will do HavingColor.getColor() anyway but on repository not the caller level).

  • Related