skip to Main Content

I have created a project with spring boot and MongoDB as database. I am trying to hit a get request to fetch the data that I have saved in the database. For fetching that I am passing an id from the from the request but the id that I am getting in the RestController method is different. Please tell me why that is the case.

Here is the object with objectId in the database:

 `{
    _id: ObjectId('66d49f49199a3f1a71d67fc8'),
    title: 'Johnny',
    content: 'Flame On!',
    _class: 'net.engineeringDigest.journalApp.entity.JournalEntry'
 }`

Object in the mongodb database

This is the GET request:

http://localhost:8080/journalV2/id?id=66d49f49199a3f1a71d67fc8

GET Reuqest

Here i am passing the id as 66d49f49199a3f1a71d67fc8

This is the RestController method with the Get Mapping

`@GetMapping("/id")
    public JournalEntry getJournalEntryById(ObjectId id) {
        return journalEntryService.findById(id).orElse(null);
    }`

RestController Method with Get Mapping

And the id i am getting in the method is a random one everytime. For eg:

66d5b4596a652065f5f0624d

I am not sure what to change in this. I have other method with GetMapping for which this is working:

enter image description here

But I want the above way to work too.

2

Answers


  1. Looks like, the issue lies in the way the id is extracted from the URL and converted to a Java object in the GET request method.

    Use the @PathVariable annotation to bind the id from the URL to the method parameter.

    Updated code,

    @GetMapping("/{id}")
        public JournalEntry getJournalEntryById(@PathVariable ObjectId id) {
        return journalEntryService.findById(id).orElse(null);
        }
    
    Login or Signup to reply.
  2. In the given GET Request

    http://localhost:8080/journalV2/id?id=66d49f49199a3f1a71d67fc8
    

    the id is sent as a parameter.

    Therefore you have to alter the GetMapping like this:

    @GetMapping("/id")
    public JournalEntry getJournalEntryById(@RequestParam("id") ObjectId id)
    {
        return journalEntryService.findById(id).orElse(null);
    }
    

    The @RequestParam annotation is used to obtain the parameters from the Http requests.

    You can refer this for more information about @RequestParam.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search