Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use @ReqeustBody with the @Query

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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?

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading